PackageManagerService.java revision 06505d234ddf66cb71d1f7defd096bdf68bc222d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS; 20import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 26import static android.system.OsConstants.S_IRWXU; 27import static android.system.OsConstants.S_IRGRP; 28import static android.system.OsConstants.S_IXGRP; 29import static android.system.OsConstants.S_IROTH; 30import static android.system.OsConstants.S_IXOTH; 31import static android.os.Process.PACKAGE_INFO_GID; 32import static android.os.Process.SYSTEM_UID; 33import static com.android.internal.util.ArrayUtils.appendInt; 34import static com.android.internal.util.ArrayUtils.removeInt; 35 36import com.android.internal.R; 37import com.android.internal.app.IMediaContainerService; 38import com.android.internal.app.ResolverActivity; 39import com.android.internal.content.NativeLibraryHelper; 40import com.android.internal.content.NativeLibraryHelper.ApkHandle; 41import com.android.internal.content.PackageHelper; 42import com.android.internal.util.FastPrintWriter; 43import com.android.internal.util.FastXmlSerializer; 44import com.android.internal.util.XmlUtils; 45import com.android.server.EventLogTags; 46import com.android.server.IntentResolver; 47import com.android.server.LocalServices; 48import com.android.server.ServiceThread; 49import com.android.server.Watchdog; 50import com.android.server.storage.DeviceStorageMonitorInternal; 51 52import org.xmlpull.v1.XmlPullParser; 53import org.xmlpull.v1.XmlPullParserException; 54import org.xmlpull.v1.XmlSerializer; 55 56import android.app.ActivityManager; 57import android.app.ActivityManagerNative; 58import android.app.IActivityManager; 59import android.app.admin.IDevicePolicyManager; 60import android.app.backup.IBackupManager; 61import android.content.BroadcastReceiver; 62import android.content.ComponentName; 63import android.content.Context; 64import android.content.IIntentReceiver; 65import android.content.Intent; 66import android.content.IntentFilter; 67import android.content.IntentSender; 68import android.content.IntentSender.SendIntentException; 69import android.content.ServiceConnection; 70import android.content.pm.ActivityInfo; 71import android.content.pm.ApplicationInfo; 72import android.content.pm.ContainerEncryptionParams; 73import android.content.pm.FeatureInfo; 74import android.content.pm.IPackageDataObserver; 75import android.content.pm.IPackageDeleteObserver; 76import android.content.pm.IPackageInstallObserver; 77import android.content.pm.IPackageManager; 78import android.content.pm.IPackageMoveObserver; 79import android.content.pm.IPackageStatsObserver; 80import android.content.pm.InstrumentationInfo; 81import android.content.pm.ManifestDigest; 82import android.content.pm.PackageCleanItem; 83import android.content.pm.PackageInfo; 84import android.content.pm.PackageInfoLite; 85import android.content.pm.PackageManager; 86import android.content.pm.PackageParser.ActivityIntentInfo; 87import android.content.pm.PackageParser; 88import android.content.pm.PackageStats; 89import android.content.pm.PackageUserState; 90import android.content.pm.ParceledListSlice; 91import android.content.pm.PermissionGroupInfo; 92import android.content.pm.PermissionInfo; 93import android.content.pm.ProviderInfo; 94import android.content.pm.ResolveInfo; 95import android.content.pm.ServiceInfo; 96import android.content.pm.Signature; 97import android.content.pm.VerificationParams; 98import android.content.pm.VerifierDeviceIdentity; 99import android.content.pm.VerifierInfo; 100import android.content.res.Resources; 101import android.hardware.display.DisplayManager; 102import android.net.Uri; 103import android.os.Binder; 104import android.os.Build; 105import android.os.Bundle; 106import android.os.Environment; 107import android.os.Environment.UserEnvironment; 108import android.os.FileObserver; 109import android.os.FileUtils; 110import android.os.Handler; 111import android.os.IBinder; 112import android.os.Looper; 113import android.os.Message; 114import android.os.Parcel; 115import android.os.ParcelFileDescriptor; 116import android.os.Process; 117import android.os.RemoteException; 118import android.os.SELinux; 119import android.os.ServiceManager; 120import android.os.SystemClock; 121import android.os.SystemProperties; 122import android.os.UserHandle; 123import android.os.UserManager; 124import android.security.KeyStore; 125import android.security.SystemKeyStore; 126import android.system.ErrnoException; 127import android.system.Os; 128import android.system.StructStat; 129import android.text.TextUtils; 130import android.util.AtomicFile; 131import android.util.DisplayMetrics; 132import android.util.EventLog; 133import android.util.Log; 134import android.util.LogPrinter; 135import android.util.PrintStreamPrinter; 136import android.util.Slog; 137import android.util.SparseArray; 138import android.util.Xml; 139import android.view.Display; 140 141import java.io.BufferedInputStream; 142import java.io.BufferedOutputStream; 143import java.io.File; 144import java.io.FileDescriptor; 145import java.io.FileInputStream; 146import java.io.FileNotFoundException; 147import java.io.FileOutputStream; 148import java.io.FileReader; 149import java.io.FilenameFilter; 150import java.io.IOException; 151import java.io.InputStream; 152import java.io.PrintWriter; 153import java.nio.charset.StandardCharsets; 154import java.security.NoSuchAlgorithmException; 155import java.security.PublicKey; 156import java.security.cert.CertificateException; 157import java.text.SimpleDateFormat; 158import java.util.ArrayList; 159import java.util.Arrays; 160import java.util.Collection; 161import java.util.Collections; 162import java.util.Comparator; 163import java.util.Date; 164import java.util.HashMap; 165import java.util.HashSet; 166import java.util.Iterator; 167import java.util.List; 168import java.util.Map; 169import java.util.Set; 170import java.util.concurrent.atomic.AtomicBoolean; 171import java.util.concurrent.atomic.AtomicLong; 172 173import dalvik.system.DexFile; 174import dalvik.system.StaleDexCacheError; 175import dalvik.system.VMRuntime; 176import libcore.io.IoUtils; 177 178/** 179 * Keep track of all those .apks everywhere. 180 * 181 * This is very central to the platform's security; please run the unit 182 * tests whenever making modifications here: 183 * 184mmm frameworks/base/tests/AndroidTests 185adb install -r -f out/target/product/passion/data/app/AndroidTests.apk 186adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner 187 * 188 * {@hide} 189 */ 190public class PackageManagerService extends IPackageManager.Stub { 191 static final String TAG = "PackageManager"; 192 static final boolean DEBUG_SETTINGS = false; 193 static final boolean DEBUG_PREFERRED = false; 194 static final boolean DEBUG_UPGRADE = false; 195 private static final boolean DEBUG_INSTALL = false; 196 private static final boolean DEBUG_REMOVE = false; 197 private static final boolean DEBUG_BROADCASTS = false; 198 private static final boolean DEBUG_SHOW_INFO = false; 199 private static final boolean DEBUG_PACKAGE_INFO = false; 200 private static final boolean DEBUG_INTENT_MATCHING = false; 201 private static final boolean DEBUG_PACKAGE_SCANNING = false; 202 private static final boolean DEBUG_APP_DIR_OBSERVER = false; 203 private static final boolean DEBUG_VERIFY = false; 204 private static final boolean DEBUG_DEXOPT = false; 205 206 private static final int RADIO_UID = Process.PHONE_UID; 207 private static final int LOG_UID = Process.LOG_UID; 208 private static final int NFC_UID = Process.NFC_UID; 209 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 210 private static final int SHELL_UID = Process.SHELL_UID; 211 212 private static final boolean GET_CERTIFICATES = true; 213 214 private static final int REMOVE_EVENTS = 215 FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM; 216 private static final int ADD_EVENTS = 217 FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO; 218 219 private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS; 220 // Suffix used during package installation when copying/moving 221 // package apks to install directory. 222 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 223 224 static final int SCAN_MONITOR = 1<<0; 225 static final int SCAN_NO_DEX = 1<<1; 226 static final int SCAN_FORCE_DEX = 1<<2; 227 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 228 static final int SCAN_NEW_INSTALL = 1<<4; 229 static final int SCAN_NO_PATHS = 1<<5; 230 static final int SCAN_UPDATE_TIME = 1<<6; 231 static final int SCAN_DEFER_DEX = 1<<7; 232 static final int SCAN_BOOTING = 1<<8; 233 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 234 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 235 236 static final int REMOVE_CHATTY = 1<<16; 237 238 /** 239 * Timeout (in milliseconds) after which the watchdog should declare that 240 * our handler thread is wedged. The usual default for such things is one 241 * minute but we sometimes do very lengthy I/O operations on this thread, 242 * such as installing multi-gigabyte applications, so ours needs to be longer. 243 */ 244 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 245 246 /** 247 * Whether verification is enabled by default. 248 */ 249 private static final boolean DEFAULT_VERIFY_ENABLE = true; 250 251 /** 252 * The default maximum time to wait for the verification agent to return in 253 * milliseconds. 254 */ 255 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 256 257 /** 258 * The default response for package verification timeout. 259 * 260 * This can be either PackageManager.VERIFICATION_ALLOW or 261 * PackageManager.VERIFICATION_REJECT. 262 */ 263 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 264 265 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 266 267 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 268 DEFAULT_CONTAINER_PACKAGE, 269 "com.android.defcontainer.DefaultContainerService"); 270 271 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 272 273 private static final String LIB_DIR_NAME = "lib"; 274 private static final String LIB64_DIR_NAME = "lib64"; 275 276 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 277 278 static final String mTempContainerPrefix = "smdl2tmp"; 279 280 final ServiceThread mHandlerThread; 281 282 private static String sPreferredInstructionSet; 283 284 private static final String IDMAP_PREFIX = "/data/resource-cache/"; 285 private static final String IDMAP_SUFFIX = "@idmap"; 286 287 final PackageHandler mHandler; 288 289 final int mSdkVersion = Build.VERSION.SDK_INT; 290 final String mSdkCodename = "REL".equals(Build.VERSION.CODENAME) 291 ? null : Build.VERSION.CODENAME; 292 293 final Context mContext; 294 final boolean mFactoryTest; 295 final boolean mOnlyCore; 296 final DisplayMetrics mMetrics; 297 final int mDefParseFlags; 298 final String[] mSeparateProcesses; 299 300 // This is where all application persistent data goes. 301 final File mAppDataDir; 302 303 // This is where all application persistent data goes for secondary users. 304 final File mUserAppDataDir; 305 306 /** The location for ASEC container files on internal storage. */ 307 final String mAsecInternalPath; 308 309 // This is the object monitoring the framework dir. 310 final FileObserver mFrameworkInstallObserver; 311 312 // This is the object monitoring the system app dir. 313 final FileObserver mSystemInstallObserver; 314 315 // This is the object monitoring the privileged system app dir. 316 final FileObserver mPrivilegedInstallObserver; 317 318 // This is the object monitoring the system app dir. 319 final FileObserver mVendorInstallObserver; 320 321 // This is the object monitoring the vendor overlay package dir. 322 final FileObserver mVendorOverlayInstallObserver; 323 324 // This is the object monitoring mAppInstallDir. 325 final FileObserver mAppInstallObserver; 326 327 // This is the object monitoring mDrmAppPrivateInstallDir. 328 final FileObserver mDrmAppInstallObserver; 329 330 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 331 // LOCK HELD. Can be called with mInstallLock held. 332 final Installer mInstaller; 333 334 final File mAppInstallDir; 335 336 /** 337 * Directory to which applications installed internally have native 338 * libraries copied. 339 */ 340 private File mAppLibInstallDir; 341 342 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 343 // apps. 344 final File mDrmAppPrivateInstallDir; 345 346 // ---------------------------------------------------------------- 347 348 // Lock for state used when installing and doing other long running 349 // operations. Methods that must be called with this lock held have 350 // the prefix "LI". 351 final Object mInstallLock = new Object(); 352 353 // These are the directories in the 3rd party applications installed dir 354 // that we have currently loaded packages from. Keys are the application's 355 // installed zip file (absolute codePath), and values are Package. 356 final HashMap<String, PackageParser.Package> mAppDirs = 357 new HashMap<String, PackageParser.Package>(); 358 359 // Information for the parser to write more useful error messages. 360 int mLastScanError; 361 362 // ---------------------------------------------------------------- 363 364 // Keys are String (package name), values are Package. This also serves 365 // as the lock for the global state. Methods that must be called with 366 // this lock held have the prefix "LP". 367 final HashMap<String, PackageParser.Package> mPackages = 368 new HashMap<String, PackageParser.Package>(); 369 370 // Tracks available target package names -> overlay package paths. 371 final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays = 372 new HashMap<String, HashMap<String, PackageParser.Package>>(); 373 374 final Settings mSettings; 375 boolean mRestoredSettings; 376 377 // Group-ids that are given to all packages as read from etc/permissions/*.xml. 378 int[] mGlobalGids; 379 380 // These are the built-in uid -> permission mappings that were read from the 381 // etc/permissions.xml file. 382 final SparseArray<HashSet<String>> mSystemPermissions = 383 new SparseArray<HashSet<String>>(); 384 385 static final class SharedLibraryEntry { 386 final String path; 387 final String apk; 388 389 SharedLibraryEntry(String _path, String _apk) { 390 path = _path; 391 apk = _apk; 392 } 393 } 394 395 // These are the built-in shared libraries that were read from the 396 // etc/permissions.xml file. 397 final HashMap<String, SharedLibraryEntry> mSharedLibraries 398 = new HashMap<String, SharedLibraryEntry>(); 399 400 // Temporary for building the final shared libraries for an .apk. 401 String[] mTmpSharedLibraries = null; 402 403 // These are the features this devices supports that were read from the 404 // etc/permissions.xml file. 405 final HashMap<String, FeatureInfo> mAvailableFeatures = 406 new HashMap<String, FeatureInfo>(); 407 408 // If mac_permissions.xml was found for seinfo labeling. 409 boolean mFoundPolicyFile; 410 411 // If a recursive restorecon of /data/data/<pkg> is needed. 412 private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon(); 413 414 // All available activities, for your resolving pleasure. 415 final ActivityIntentResolver mActivities = 416 new ActivityIntentResolver(); 417 418 // All available receivers, for your resolving pleasure. 419 final ActivityIntentResolver mReceivers = 420 new ActivityIntentResolver(); 421 422 // All available services, for your resolving pleasure. 423 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 424 425 // All available providers, for your resolving pleasure. 426 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 427 428 // Mapping from provider base names (first directory in content URI codePath) 429 // to the provider information. 430 final HashMap<String, PackageParser.Provider> mProvidersByAuthority = 431 new HashMap<String, PackageParser.Provider>(); 432 433 // Mapping from instrumentation class names to info about them. 434 final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 435 new HashMap<ComponentName, PackageParser.Instrumentation>(); 436 437 // Mapping from permission names to info about them. 438 final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups = 439 new HashMap<String, PackageParser.PermissionGroup>(); 440 441 // Packages whose data we have transfered into another package, thus 442 // should no longer exist. 443 final HashSet<String> mTransferedPackages = new HashSet<String>(); 444 445 // Broadcast actions that are only available to the system. 446 final HashSet<String> mProtectedBroadcasts = new HashSet<String>(); 447 448 /** List of packages waiting for verification. */ 449 final SparseArray<PackageVerificationState> mPendingVerification 450 = new SparseArray<PackageVerificationState>(); 451 452 HashSet<PackageParser.Package> mDeferredDexOpt = null; 453 454 /** Token for keys in mPendingVerification. */ 455 private int mPendingVerificationToken = 0; 456 457 boolean mSystemReady; 458 boolean mSafeMode; 459 boolean mHasSystemUidErrors; 460 461 ApplicationInfo mAndroidApplication; 462 final ActivityInfo mResolveActivity = new ActivityInfo(); 463 final ResolveInfo mResolveInfo = new ResolveInfo(); 464 ComponentName mResolveComponentName; 465 PackageParser.Package mPlatformPackage; 466 ComponentName mCustomResolverComponentName; 467 468 boolean mResolverReplaced = false; 469 470 // Set of pending broadcasts for aggregating enable/disable of components. 471 static class PendingPackageBroadcasts { 472 // for each user id, a map of <package name -> components within that package> 473 final SparseArray<HashMap<String, ArrayList<String>>> mUidMap; 474 475 public PendingPackageBroadcasts() { 476 mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2); 477 } 478 479 public ArrayList<String> get(int userId, String packageName) { 480 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 481 return packages.get(packageName); 482 } 483 484 public void put(int userId, String packageName, ArrayList<String> components) { 485 HashMap<String, ArrayList<String>> packages = getOrAllocate(userId); 486 packages.put(packageName, components); 487 } 488 489 public void remove(int userId, String packageName) { 490 HashMap<String, ArrayList<String>> packages = mUidMap.get(userId); 491 if (packages != null) { 492 packages.remove(packageName); 493 } 494 } 495 496 public void remove(int userId) { 497 mUidMap.remove(userId); 498 } 499 500 public int userIdCount() { 501 return mUidMap.size(); 502 } 503 504 public int userIdAt(int n) { 505 return mUidMap.keyAt(n); 506 } 507 508 public HashMap<String, ArrayList<String>> packagesForUserId(int userId) { 509 return mUidMap.get(userId); 510 } 511 512 public int size() { 513 // total number of pending broadcast entries across all userIds 514 int num = 0; 515 for (int i = 0; i< mUidMap.size(); i++) { 516 num += mUidMap.valueAt(i).size(); 517 } 518 return num; 519 } 520 521 public void clear() { 522 mUidMap.clear(); 523 } 524 525 private HashMap<String, ArrayList<String>> getOrAllocate(int userId) { 526 HashMap<String, ArrayList<String>> map = mUidMap.get(userId); 527 if (map == null) { 528 map = new HashMap<String, ArrayList<String>>(); 529 mUidMap.put(userId, map); 530 } 531 return map; 532 } 533 } 534 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 535 536 // Service Connection to remote media container service to copy 537 // package uri's from external media onto secure containers 538 // or internal storage. 539 private IMediaContainerService mContainerService = null; 540 541 static final int SEND_PENDING_BROADCAST = 1; 542 static final int MCS_BOUND = 3; 543 static final int END_COPY = 4; 544 static final int INIT_COPY = 5; 545 static final int MCS_UNBIND = 6; 546 static final int START_CLEANING_PACKAGE = 7; 547 static final int FIND_INSTALL_LOC = 8; 548 static final int POST_INSTALL = 9; 549 static final int MCS_RECONNECT = 10; 550 static final int MCS_GIVE_UP = 11; 551 static final int UPDATED_MEDIA_STATUS = 12; 552 static final int WRITE_SETTINGS = 13; 553 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 554 static final int PACKAGE_VERIFIED = 15; 555 static final int CHECK_PENDING_VERIFICATION = 16; 556 557 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 558 559 // Delay time in millisecs 560 static final int BROADCAST_DELAY = 10 * 1000; 561 562 static UserManagerService sUserManager; 563 564 // Stores a list of users whose package restrictions file needs to be updated 565 private HashSet<Integer> mDirtyUsers = new HashSet<Integer>(); 566 567 final private DefaultContainerConnection mDefContainerConn = 568 new DefaultContainerConnection(); 569 class DefaultContainerConnection implements ServiceConnection { 570 public void onServiceConnected(ComponentName name, IBinder service) { 571 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 572 IMediaContainerService imcs = 573 IMediaContainerService.Stub.asInterface(service); 574 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 575 } 576 577 public void onServiceDisconnected(ComponentName name) { 578 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 579 } 580 }; 581 582 // Recordkeeping of restore-after-install operations that are currently in flight 583 // between the Package Manager and the Backup Manager 584 class PostInstallData { 585 public InstallArgs args; 586 public PackageInstalledInfo res; 587 588 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 589 args = _a; 590 res = _r; 591 } 592 }; 593 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 594 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 595 596 private final String mRequiredVerifierPackage; 597 598 private final PackageUsage mPackageUsage = new PackageUsage(); 599 600 private class PackageUsage { 601 private static final int WRITE_INTERVAL 602 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 603 604 private final Object mFileLock = new Object(); 605 private final AtomicLong mLastWritten = new AtomicLong(0); 606 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 607 608 private boolean mIsHistoricalPackageUsageAvailable = true; 609 610 boolean isHistoricalPackageUsageAvailable() { 611 return mIsHistoricalPackageUsageAvailable; 612 } 613 614 void write(boolean force) { 615 if (force) { 616 writeInternal(); 617 return; 618 } 619 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 620 && !DEBUG_DEXOPT) { 621 return; 622 } 623 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 624 new Thread("PackageUsage_DiskWriter") { 625 @Override 626 public void run() { 627 try { 628 writeInternal(); 629 } finally { 630 mBackgroundWriteRunning.set(false); 631 } 632 } 633 }.start(); 634 } 635 } 636 637 private void writeInternal() { 638 synchronized (mPackages) { 639 synchronized (mFileLock) { 640 AtomicFile file = getFile(); 641 FileOutputStream f = null; 642 try { 643 f = file.startWrite(); 644 BufferedOutputStream out = new BufferedOutputStream(f); 645 FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID); 646 StringBuilder sb = new StringBuilder(); 647 for (PackageParser.Package pkg : mPackages.values()) { 648 if (pkg.mLastPackageUsageTimeInMills == 0) { 649 continue; 650 } 651 sb.setLength(0); 652 sb.append(pkg.packageName); 653 sb.append(' '); 654 sb.append((long)pkg.mLastPackageUsageTimeInMills); 655 sb.append('\n'); 656 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 657 } 658 out.flush(); 659 file.finishWrite(f); 660 } catch (IOException e) { 661 if (f != null) { 662 file.failWrite(f); 663 } 664 Log.e(TAG, "Failed to write package usage times", e); 665 } 666 } 667 } 668 mLastWritten.set(SystemClock.elapsedRealtime()); 669 } 670 671 void readLP() { 672 synchronized (mFileLock) { 673 AtomicFile file = getFile(); 674 BufferedInputStream in = null; 675 try { 676 in = new BufferedInputStream(file.openRead()); 677 StringBuffer sb = new StringBuffer(); 678 while (true) { 679 String packageName = readToken(in, sb, ' '); 680 if (packageName == null) { 681 break; 682 } 683 String timeInMillisString = readToken(in, sb, '\n'); 684 if (timeInMillisString == null) { 685 throw new IOException("Failed to find last usage time for package " 686 + packageName); 687 } 688 PackageParser.Package pkg = mPackages.get(packageName); 689 if (pkg == null) { 690 continue; 691 } 692 long timeInMillis; 693 try { 694 timeInMillis = Long.parseLong(timeInMillisString.toString()); 695 } catch (NumberFormatException e) { 696 throw new IOException("Failed to parse " + timeInMillisString 697 + " as a long.", e); 698 } 699 pkg.mLastPackageUsageTimeInMills = timeInMillis; 700 } 701 } catch (FileNotFoundException expected) { 702 mIsHistoricalPackageUsageAvailable = false; 703 } catch (IOException e) { 704 Log.w(TAG, "Failed to read package usage times", e); 705 } finally { 706 IoUtils.closeQuietly(in); 707 } 708 } 709 mLastWritten.set(SystemClock.elapsedRealtime()); 710 } 711 712 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 713 throws IOException { 714 sb.setLength(0); 715 while (true) { 716 int ch = in.read(); 717 if (ch == -1) { 718 if (sb.length() == 0) { 719 return null; 720 } 721 throw new IOException("Unexpected EOF"); 722 } 723 if (ch == endOfToken) { 724 return sb.toString(); 725 } 726 sb.append((char)ch); 727 } 728 } 729 730 private AtomicFile getFile() { 731 File dataDir = Environment.getDataDirectory(); 732 File systemDir = new File(dataDir, "system"); 733 File fname = new File(systemDir, "package-usage.list"); 734 return new AtomicFile(fname); 735 } 736 } 737 738 class PackageHandler extends Handler { 739 private boolean mBound = false; 740 final ArrayList<HandlerParams> mPendingInstalls = 741 new ArrayList<HandlerParams>(); 742 743 private boolean connectToService() { 744 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 745 " DefaultContainerService"); 746 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 747 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 748 if (mContext.bindServiceAsUser(service, mDefContainerConn, 749 Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 750 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 751 mBound = true; 752 return true; 753 } 754 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 755 return false; 756 } 757 758 private void disconnectService() { 759 mContainerService = null; 760 mBound = false; 761 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 762 mContext.unbindService(mDefContainerConn); 763 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 764 } 765 766 PackageHandler(Looper looper) { 767 super(looper); 768 } 769 770 public void handleMessage(Message msg) { 771 try { 772 doHandleMessage(msg); 773 } finally { 774 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 775 } 776 } 777 778 void doHandleMessage(Message msg) { 779 switch (msg.what) { 780 case INIT_COPY: { 781 HandlerParams params = (HandlerParams) msg.obj; 782 int idx = mPendingInstalls.size(); 783 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 784 // If a bind was already initiated we dont really 785 // need to do anything. The pending install 786 // will be processed later on. 787 if (!mBound) { 788 // If this is the only one pending we might 789 // have to bind to the service again. 790 if (!connectToService()) { 791 Slog.e(TAG, "Failed to bind to media container service"); 792 params.serviceError(); 793 return; 794 } else { 795 // Once we bind to the service, the first 796 // pending request will be processed. 797 mPendingInstalls.add(idx, params); 798 } 799 } else { 800 mPendingInstalls.add(idx, params); 801 // Already bound to the service. Just make 802 // sure we trigger off processing the first request. 803 if (idx == 0) { 804 mHandler.sendEmptyMessage(MCS_BOUND); 805 } 806 } 807 break; 808 } 809 case MCS_BOUND: { 810 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 811 if (msg.obj != null) { 812 mContainerService = (IMediaContainerService) msg.obj; 813 } 814 if (mContainerService == null) { 815 // Something seriously wrong. Bail out 816 Slog.e(TAG, "Cannot bind to media container service"); 817 for (HandlerParams params : mPendingInstalls) { 818 // Indicate service bind error 819 params.serviceError(); 820 } 821 mPendingInstalls.clear(); 822 } else if (mPendingInstalls.size() > 0) { 823 HandlerParams params = mPendingInstalls.get(0); 824 if (params != null) { 825 if (params.startCopy()) { 826 // We are done... look for more work or to 827 // go idle. 828 if (DEBUG_SD_INSTALL) Log.i(TAG, 829 "Checking for more work or unbind..."); 830 // Delete pending install 831 if (mPendingInstalls.size() > 0) { 832 mPendingInstalls.remove(0); 833 } 834 if (mPendingInstalls.size() == 0) { 835 if (mBound) { 836 if (DEBUG_SD_INSTALL) Log.i(TAG, 837 "Posting delayed MCS_UNBIND"); 838 removeMessages(MCS_UNBIND); 839 Message ubmsg = obtainMessage(MCS_UNBIND); 840 // Unbind after a little delay, to avoid 841 // continual thrashing. 842 sendMessageDelayed(ubmsg, 10000); 843 } 844 } else { 845 // There are more pending requests in queue. 846 // Just post MCS_BOUND message to trigger processing 847 // of next pending install. 848 if (DEBUG_SD_INSTALL) Log.i(TAG, 849 "Posting MCS_BOUND for next woek"); 850 mHandler.sendEmptyMessage(MCS_BOUND); 851 } 852 } 853 } 854 } else { 855 // Should never happen ideally. 856 Slog.w(TAG, "Empty queue"); 857 } 858 break; 859 } 860 case MCS_RECONNECT: { 861 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 862 if (mPendingInstalls.size() > 0) { 863 if (mBound) { 864 disconnectService(); 865 } 866 if (!connectToService()) { 867 Slog.e(TAG, "Failed to bind to media container service"); 868 for (HandlerParams params : mPendingInstalls) { 869 // Indicate service bind error 870 params.serviceError(); 871 } 872 mPendingInstalls.clear(); 873 } 874 } 875 break; 876 } 877 case MCS_UNBIND: { 878 // If there is no actual work left, then time to unbind. 879 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 880 881 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 882 if (mBound) { 883 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 884 885 disconnectService(); 886 } 887 } else if (mPendingInstalls.size() > 0) { 888 // There are more pending requests in queue. 889 // Just post MCS_BOUND message to trigger processing 890 // of next pending install. 891 mHandler.sendEmptyMessage(MCS_BOUND); 892 } 893 894 break; 895 } 896 case MCS_GIVE_UP: { 897 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 898 mPendingInstalls.remove(0); 899 break; 900 } 901 case SEND_PENDING_BROADCAST: { 902 String packages[]; 903 ArrayList<String> components[]; 904 int size = 0; 905 int uids[]; 906 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 907 synchronized (mPackages) { 908 if (mPendingBroadcasts == null) { 909 return; 910 } 911 size = mPendingBroadcasts.size(); 912 if (size <= 0) { 913 // Nothing to be done. Just return 914 return; 915 } 916 packages = new String[size]; 917 components = new ArrayList[size]; 918 uids = new int[size]; 919 int i = 0; // filling out the above arrays 920 921 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 922 int packageUserId = mPendingBroadcasts.userIdAt(n); 923 Iterator<Map.Entry<String, ArrayList<String>>> it 924 = mPendingBroadcasts.packagesForUserId(packageUserId) 925 .entrySet().iterator(); 926 while (it.hasNext() && i < size) { 927 Map.Entry<String, ArrayList<String>> ent = it.next(); 928 packages[i] = ent.getKey(); 929 components[i] = ent.getValue(); 930 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 931 uids[i] = (ps != null) 932 ? UserHandle.getUid(packageUserId, ps.appId) 933 : -1; 934 i++; 935 } 936 } 937 size = i; 938 mPendingBroadcasts.clear(); 939 } 940 // Send broadcasts 941 for (int i = 0; i < size; i++) { 942 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 943 } 944 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 945 break; 946 } 947 case START_CLEANING_PACKAGE: { 948 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 949 final String packageName = (String)msg.obj; 950 final int userId = msg.arg1; 951 final boolean andCode = msg.arg2 != 0; 952 synchronized (mPackages) { 953 if (userId == UserHandle.USER_ALL) { 954 int[] users = sUserManager.getUserIds(); 955 for (int user : users) { 956 mSettings.addPackageToCleanLPw( 957 new PackageCleanItem(user, packageName, andCode)); 958 } 959 } else { 960 mSettings.addPackageToCleanLPw( 961 new PackageCleanItem(userId, packageName, andCode)); 962 } 963 } 964 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 965 startCleaningPackages(); 966 } break; 967 case POST_INSTALL: { 968 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 969 PostInstallData data = mRunningInstalls.get(msg.arg1); 970 mRunningInstalls.delete(msg.arg1); 971 boolean deleteOld = false; 972 973 if (data != null) { 974 InstallArgs args = data.args; 975 PackageInstalledInfo res = data.res; 976 977 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 978 res.removedInfo.sendBroadcast(false, true, false); 979 Bundle extras = new Bundle(1); 980 extras.putInt(Intent.EXTRA_UID, res.uid); 981 // Determine the set of users who are adding this 982 // package for the first time vs. those who are seeing 983 // an update. 984 int[] firstUsers; 985 int[] updateUsers = new int[0]; 986 if (res.origUsers == null || res.origUsers.length == 0) { 987 firstUsers = res.newUsers; 988 } else { 989 firstUsers = new int[0]; 990 for (int i=0; i<res.newUsers.length; i++) { 991 int user = res.newUsers[i]; 992 boolean isNew = true; 993 for (int j=0; j<res.origUsers.length; j++) { 994 if (res.origUsers[j] == user) { 995 isNew = false; 996 break; 997 } 998 } 999 if (isNew) { 1000 int[] newFirst = new int[firstUsers.length+1]; 1001 System.arraycopy(firstUsers, 0, newFirst, 0, 1002 firstUsers.length); 1003 newFirst[firstUsers.length] = user; 1004 firstUsers = newFirst; 1005 } else { 1006 int[] newUpdate = new int[updateUsers.length+1]; 1007 System.arraycopy(updateUsers, 0, newUpdate, 0, 1008 updateUsers.length); 1009 newUpdate[updateUsers.length] = user; 1010 updateUsers = newUpdate; 1011 } 1012 } 1013 } 1014 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1015 res.pkg.applicationInfo.packageName, 1016 extras, null, null, firstUsers); 1017 final boolean update = res.removedInfo.removedPackage != null; 1018 if (update) { 1019 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1020 } 1021 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 1022 res.pkg.applicationInfo.packageName, 1023 extras, null, null, updateUsers); 1024 if (update) { 1025 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1026 res.pkg.applicationInfo.packageName, 1027 extras, null, null, updateUsers); 1028 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1029 null, null, 1030 res.pkg.applicationInfo.packageName, null, updateUsers); 1031 1032 // treat asec-hosted packages like removable media on upgrade 1033 if (isForwardLocked(res.pkg) || isExternal(res.pkg)) { 1034 if (DEBUG_INSTALL) { 1035 Slog.i(TAG, "upgrading pkg " + res.pkg 1036 + " is ASEC-hosted -> AVAILABLE"); 1037 } 1038 int[] uidArray = new int[] { res.pkg.applicationInfo.uid }; 1039 ArrayList<String> pkgList = new ArrayList<String>(1); 1040 pkgList.add(res.pkg.applicationInfo.packageName); 1041 sendResourcesChangedBroadcast(true, true, 1042 pkgList,uidArray, null); 1043 } 1044 } 1045 if (res.removedInfo.args != null) { 1046 // Remove the replaced package's older resources safely now 1047 deleteOld = true; 1048 } 1049 1050 // Log current value of "unknown sources" setting 1051 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1052 getUnknownSourcesSettings()); 1053 } 1054 // Force a gc to clear up things 1055 Runtime.getRuntime().gc(); 1056 // We delete after a gc for applications on sdcard. 1057 if (deleteOld) { 1058 synchronized (mInstallLock) { 1059 res.removedInfo.args.doPostDeleteLI(true); 1060 } 1061 } 1062 if (args.observer != null) { 1063 try { 1064 args.observer.packageInstalled(res.name, res.returnCode); 1065 } catch (RemoteException e) { 1066 Slog.i(TAG, "Observer no longer exists."); 1067 } 1068 } 1069 } else { 1070 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1071 } 1072 } break; 1073 case UPDATED_MEDIA_STATUS: { 1074 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1075 boolean reportStatus = msg.arg1 == 1; 1076 boolean doGc = msg.arg2 == 1; 1077 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1078 if (doGc) { 1079 // Force a gc to clear up stale containers. 1080 Runtime.getRuntime().gc(); 1081 } 1082 if (msg.obj != null) { 1083 @SuppressWarnings("unchecked") 1084 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1085 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1086 // Unload containers 1087 unloadAllContainers(args); 1088 } 1089 if (reportStatus) { 1090 try { 1091 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1092 PackageHelper.getMountService().finishMediaUpdate(); 1093 } catch (RemoteException e) { 1094 Log.e(TAG, "MountService not running?"); 1095 } 1096 } 1097 } break; 1098 case WRITE_SETTINGS: { 1099 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1100 synchronized (mPackages) { 1101 removeMessages(WRITE_SETTINGS); 1102 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1103 mSettings.writeLPr(); 1104 mDirtyUsers.clear(); 1105 } 1106 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1107 } break; 1108 case WRITE_PACKAGE_RESTRICTIONS: { 1109 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1110 synchronized (mPackages) { 1111 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1112 for (int userId : mDirtyUsers) { 1113 mSettings.writePackageRestrictionsLPr(userId); 1114 } 1115 mDirtyUsers.clear(); 1116 } 1117 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1118 } break; 1119 case CHECK_PENDING_VERIFICATION: { 1120 final int verificationId = msg.arg1; 1121 final PackageVerificationState state = mPendingVerification.get(verificationId); 1122 1123 if ((state != null) && !state.timeoutExtended()) { 1124 final InstallArgs args = state.getInstallArgs(); 1125 Slog.i(TAG, "Verification timed out for " + args.packageURI.toString()); 1126 mPendingVerification.remove(verificationId); 1127 1128 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1129 1130 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1131 Slog.i(TAG, "Continuing with installation of " 1132 + args.packageURI.toString()); 1133 state.setVerifierResponse(Binder.getCallingUid(), 1134 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1135 broadcastPackageVerified(verificationId, args.packageURI, 1136 PackageManager.VERIFICATION_ALLOW, 1137 state.getInstallArgs().getUser()); 1138 try { 1139 ret = args.copyApk(mContainerService, true); 1140 } catch (RemoteException e) { 1141 Slog.e(TAG, "Could not contact the ContainerService"); 1142 } 1143 } else { 1144 broadcastPackageVerified(verificationId, args.packageURI, 1145 PackageManager.VERIFICATION_REJECT, 1146 state.getInstallArgs().getUser()); 1147 } 1148 1149 processPendingInstall(args, ret); 1150 mHandler.sendEmptyMessage(MCS_UNBIND); 1151 } 1152 break; 1153 } 1154 case PACKAGE_VERIFIED: { 1155 final int verificationId = msg.arg1; 1156 1157 final PackageVerificationState state = mPendingVerification.get(verificationId); 1158 if (state == null) { 1159 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1160 break; 1161 } 1162 1163 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1164 1165 state.setVerifierResponse(response.callerUid, response.code); 1166 1167 if (state.isVerificationComplete()) { 1168 mPendingVerification.remove(verificationId); 1169 1170 final InstallArgs args = state.getInstallArgs(); 1171 1172 int ret; 1173 if (state.isInstallAllowed()) { 1174 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1175 broadcastPackageVerified(verificationId, args.packageURI, 1176 response.code, state.getInstallArgs().getUser()); 1177 try { 1178 ret = args.copyApk(mContainerService, true); 1179 } catch (RemoteException e) { 1180 Slog.e(TAG, "Could not contact the ContainerService"); 1181 } 1182 } else { 1183 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1184 } 1185 1186 processPendingInstall(args, ret); 1187 1188 mHandler.sendEmptyMessage(MCS_UNBIND); 1189 } 1190 1191 break; 1192 } 1193 } 1194 } 1195 } 1196 1197 void scheduleWriteSettingsLocked() { 1198 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1199 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1200 } 1201 } 1202 1203 void scheduleWritePackageRestrictionsLocked(int userId) { 1204 if (!sUserManager.exists(userId)) return; 1205 mDirtyUsers.add(userId); 1206 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1207 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1208 } 1209 } 1210 1211 public static final IPackageManager main(Context context, Installer installer, 1212 boolean factoryTest, boolean onlyCore) { 1213 PackageManagerService m = new PackageManagerService(context, installer, 1214 factoryTest, onlyCore); 1215 ServiceManager.addService("package", m); 1216 return m; 1217 } 1218 1219 static String[] splitString(String str, char sep) { 1220 int count = 1; 1221 int i = 0; 1222 while ((i=str.indexOf(sep, i)) >= 0) { 1223 count++; 1224 i++; 1225 } 1226 1227 String[] res = new String[count]; 1228 i=0; 1229 count = 0; 1230 int lastI=0; 1231 while ((i=str.indexOf(sep, i)) >= 0) { 1232 res[count] = str.substring(lastI, i); 1233 count++; 1234 i++; 1235 lastI = i; 1236 } 1237 res[count] = str.substring(lastI, str.length()); 1238 return res; 1239 } 1240 1241 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 1242 DisplayManager displayManager = (DisplayManager) context.getSystemService( 1243 Context.DISPLAY_SERVICE); 1244 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 1245 } 1246 1247 public PackageManagerService(Context context, Installer installer, 1248 boolean factoryTest, boolean onlyCore) { 1249 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1250 SystemClock.uptimeMillis()); 1251 1252 if (mSdkVersion <= 0) { 1253 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1254 } 1255 1256 mContext = context; 1257 mFactoryTest = factoryTest; 1258 mOnlyCore = onlyCore; 1259 mMetrics = new DisplayMetrics(); 1260 mSettings = new Settings(context); 1261 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1262 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1263 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1264 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1265 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1266 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1267 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1268 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1269 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1270 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1271 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1272 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED); 1273 1274 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1275 if (separateProcesses != null && separateProcesses.length() > 0) { 1276 if ("*".equals(separateProcesses)) { 1277 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 1278 mSeparateProcesses = null; 1279 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1280 } else { 1281 mDefParseFlags = 0; 1282 mSeparateProcesses = separateProcesses.split(","); 1283 Slog.w(TAG, "Running with debug.separate_processes: " 1284 + separateProcesses); 1285 } 1286 } else { 1287 mDefParseFlags = 0; 1288 mSeparateProcesses = null; 1289 } 1290 1291 mInstaller = installer; 1292 1293 getDefaultDisplayMetrics(context, mMetrics); 1294 1295 synchronized (mInstallLock) { 1296 // writer 1297 synchronized (mPackages) { 1298 mHandlerThread = new ServiceThread(TAG, 1299 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1300 mHandlerThread.start(); 1301 mHandler = new PackageHandler(mHandlerThread.getLooper()); 1302 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 1303 1304 File dataDir = Environment.getDataDirectory(); 1305 mAppDataDir = new File(dataDir, "data"); 1306 mAppInstallDir = new File(dataDir, "app"); 1307 mAppLibInstallDir = new File(dataDir, "app-lib"); 1308 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1309 mUserAppDataDir = new File(dataDir, "user"); 1310 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1311 1312 sUserManager = new UserManagerService(context, this, 1313 mInstallLock, mPackages); 1314 1315 readPermissions(); 1316 1317 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 1318 1319 mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false), 1320 mSdkVersion, mOnlyCore); 1321 1322 String customResolverActivity = Resources.getSystem().getString( 1323 R.string.config_customResolverActivity); 1324 if (TextUtils.isEmpty(customResolverActivity)) { 1325 customResolverActivity = null; 1326 } else { 1327 mCustomResolverComponentName = ComponentName.unflattenFromString( 1328 customResolverActivity); 1329 } 1330 1331 long startTime = SystemClock.uptimeMillis(); 1332 1333 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1334 startTime); 1335 1336 // Set flag to monitor and not change apk file paths when 1337 // scanning install directories. 1338 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1339 1340 final HashSet<String> alreadyDexOpted = new HashSet<String>(); 1341 1342 /** 1343 * Add everything in the in the boot class path to the 1344 * list of process files because dexopt will have been run 1345 * if necessary during zygote startup. 1346 */ 1347 String bootClassPath = System.getProperty("java.boot.class.path"); 1348 if (bootClassPath != null) { 1349 String[] paths = splitString(bootClassPath, ':'); 1350 for (int i=0; i<paths.length; i++) { 1351 alreadyDexOpted.add(paths[i]); 1352 } 1353 } else { 1354 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1355 } 1356 1357 boolean didDexOptLibraryOrTool = false; 1358 1359 final List<String> instructionSets = getAllInstructionSets(); 1360 1361 /** 1362 * Ensure all external libraries have had dexopt run on them. 1363 */ 1364 if (mSharedLibraries.size() > 0) { 1365 // NOTE: For now, we're compiling these system "shared libraries" 1366 // (and framework jars) into all available architectures. It's possible 1367 // to compile them only when we come across an app that uses them (there's 1368 // already logic for that in scanPackageLI) but that adds some complexity. 1369 for (String instructionSet : instructionSets) { 1370 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 1371 final String lib = libEntry.path; 1372 if (lib == null) { 1373 continue; 1374 } 1375 1376 try { 1377 if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) { 1378 alreadyDexOpted.add(lib); 1379 1380 // The list of "shared libraries" we have at this point is 1381 mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet); 1382 didDexOptLibraryOrTool = true; 1383 } 1384 } catch (FileNotFoundException e) { 1385 Slog.w(TAG, "Library not found: " + lib); 1386 } catch (IOException e) { 1387 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1388 + e.getMessage()); 1389 } 1390 } 1391 } 1392 } 1393 1394 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 1395 1396 // Gross hack for now: we know this file doesn't contain any 1397 // code, so don't dexopt it to avoid the resulting log spew. 1398 alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk"); 1399 1400 // Gross hack for now: we know this file is only part of 1401 // the boot class path for art, so don't dexopt it to 1402 // avoid the resulting log spew. 1403 alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar"); 1404 1405 /** 1406 * And there are a number of commands implemented in Java, which 1407 * we currently need to do the dexopt on so that they can be 1408 * run from a non-root shell. 1409 */ 1410 String[] frameworkFiles = frameworkDir.list(); 1411 if (frameworkFiles != null) { 1412 // TODO: We could compile these only for the most preferred ABI. We should 1413 // first double check that the dex files for these commands are not referenced 1414 // by other system apps. 1415 for (String instructionSet : instructionSets) { 1416 for (int i=0; i<frameworkFiles.length; i++) { 1417 File libPath = new File(frameworkDir, frameworkFiles[i]); 1418 String path = libPath.getPath(); 1419 // Skip the file if we already did it. 1420 if (alreadyDexOpted.contains(path)) { 1421 continue; 1422 } 1423 // Skip the file if it is not a type we want to dexopt. 1424 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1425 continue; 1426 } 1427 try { 1428 if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) { 1429 mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet); 1430 didDexOptLibraryOrTool = true; 1431 } 1432 } catch (FileNotFoundException e) { 1433 Slog.w(TAG, "Jar not found: " + path); 1434 } catch (IOException e) { 1435 Slog.w(TAG, "Exception reading jar: " + path, e); 1436 } 1437 } 1438 } 1439 } 1440 1441 if (didDexOptLibraryOrTool) { 1442 // If we dexopted a library or tool, then something on the system has 1443 // changed. Consider this significant, and wipe away all other 1444 // existing dexopt files to ensure we don't leave any dangling around. 1445 // 1446 // TODO: This should be revisited because it isn't as good an indicator 1447 // as it used to be. It used to include the boot classpath but at some point 1448 // DexFile.isDexOptNeeded started returning false for the boot 1449 // class path files in all cases. It is very possible in a 1450 // small maintenance release update that the library and tool 1451 // jars may be unchanged but APK could be removed resulting in 1452 // unused dalvik-cache files. 1453 for (String instructionSet : instructionSets) { 1454 mInstaller.pruneDexCache(instructionSet); 1455 } 1456 1457 // Additionally, delete all dex files from the root directory 1458 // since there shouldn't be any there anyway, unless we're upgrading 1459 // from an older OS version or a build that contained the "old" style 1460 // flat scheme. 1461 mInstaller.pruneDexCache("."); 1462 } 1463 1464 // Collect vendor overlay packages. 1465 // (Do this before scanning any apps.) 1466 // For security and version matching reason, only consider 1467 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 1468 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 1469 mVendorOverlayInstallObserver = new AppDirObserver( 1470 vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false); 1471 mVendorOverlayInstallObserver.startWatching(); 1472 scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 1473 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0); 1474 1475 // Find base frameworks (resource packages without code). 1476 mFrameworkInstallObserver = new AppDirObserver( 1477 frameworkDir.getPath(), OBSERVER_EVENTS, true, false); 1478 mFrameworkInstallObserver.startWatching(); 1479 scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 1480 | PackageParser.PARSE_IS_SYSTEM_DIR 1481 | PackageParser.PARSE_IS_PRIVILEGED, 1482 scanMode | SCAN_NO_DEX, 0); 1483 1484 // Collected privileged system packages. 1485 File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 1486 mPrivilegedInstallObserver = new AppDirObserver( 1487 privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true); 1488 mPrivilegedInstallObserver.startWatching(); 1489 scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 1490 | PackageParser.PARSE_IS_SYSTEM_DIR 1491 | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0); 1492 1493 // Collect ordinary system packages. 1494 File systemAppDir = new File(Environment.getRootDirectory(), "app"); 1495 mSystemInstallObserver = new AppDirObserver( 1496 systemAppDir.getPath(), OBSERVER_EVENTS, true, false); 1497 mSystemInstallObserver.startWatching(); 1498 scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 1499 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1500 1501 // Collect all vendor packages. 1502 File vendorAppDir = new File("/vendor/app"); 1503 try { 1504 vendorAppDir = vendorAppDir.getCanonicalFile(); 1505 } catch (IOException e) { 1506 // failed to look up canonical path, continue with original one 1507 } 1508 mVendorInstallObserver = new AppDirObserver( 1509 vendorAppDir.getPath(), OBSERVER_EVENTS, true, false); 1510 mVendorInstallObserver.startWatching(); 1511 scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 1512 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1513 1514 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1515 mInstaller.moveFiles(); 1516 1517 // Prune any system packages that no longer exist. 1518 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1519 if (!mOnlyCore) { 1520 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1521 while (psit.hasNext()) { 1522 PackageSetting ps = psit.next(); 1523 1524 /* 1525 * If this is not a system app, it can't be a 1526 * disable system app. 1527 */ 1528 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1529 continue; 1530 } 1531 1532 /* 1533 * If the package is scanned, it's not erased. 1534 */ 1535 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1536 if (scannedPkg != null) { 1537 /* 1538 * If the system app is both scanned and in the 1539 * disabled packages list, then it must have been 1540 * added via OTA. Remove it from the currently 1541 * scanned package so the previously user-installed 1542 * application can be scanned. 1543 */ 1544 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1545 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1546 + "; removing system app"); 1547 removePackageLI(ps, true); 1548 } 1549 1550 continue; 1551 } 1552 1553 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1554 psit.remove(); 1555 String msg = "System package " + ps.name 1556 + " no longer exists; wiping its data"; 1557 reportSettingsProblem(Log.WARN, msg); 1558 removeDataDirsLI(ps.name); 1559 } else { 1560 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1561 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1562 possiblyDeletedUpdatedSystemApps.add(ps.name); 1563 } 1564 } 1565 } 1566 } 1567 1568 //look for any incomplete package installations 1569 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 1570 //clean up list 1571 for(int i = 0; i < deletePkgsList.size(); i++) { 1572 //clean up here 1573 cleanupInstallFailedPackage(deletePkgsList.get(i)); 1574 } 1575 //delete tmp files 1576 deleteTempPackageFiles(); 1577 1578 // Remove any shared userIDs that have no associated packages 1579 mSettings.pruneSharedUsersLPw(); 1580 1581 if (!mOnlyCore) { 1582 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 1583 SystemClock.uptimeMillis()); 1584 mAppInstallObserver = new AppDirObserver( 1585 mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1586 mAppInstallObserver.startWatching(); 1587 scanDirLI(mAppInstallDir, 0, scanMode, 0); 1588 1589 mDrmAppInstallObserver = new AppDirObserver( 1590 mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false); 1591 mDrmAppInstallObserver.startWatching(); 1592 scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 1593 scanMode, 0); 1594 1595 /** 1596 * Remove disable package settings for any updated system 1597 * apps that were removed via an OTA. If they're not a 1598 * previously-updated app, remove them completely. 1599 * Otherwise, just revoke their system-level permissions. 1600 */ 1601 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 1602 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 1603 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 1604 1605 String msg; 1606 if (deletedPkg == null) { 1607 msg = "Updated system package " + deletedAppName 1608 + " no longer exists; wiping its data"; 1609 removeDataDirsLI(deletedAppName); 1610 } else { 1611 msg = "Updated system app + " + deletedAppName 1612 + " no longer present; removing system privileges for " 1613 + deletedAppName; 1614 1615 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 1616 1617 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 1618 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 1619 } 1620 reportSettingsProblem(Log.WARN, msg); 1621 } 1622 } else { 1623 mAppInstallObserver = null; 1624 mDrmAppInstallObserver = null; 1625 } 1626 1627 // Now that we know all of the shared libraries, update all clients to have 1628 // the correct library paths. 1629 updateAllSharedLibrariesLPw(); 1630 1631 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 1632 // NOTE: We ignore potential failures here during a system scan (like 1633 // the rest of the commands above) because there's precious little we 1634 // can do about it. A settings error is reported, though. 1635 adjustCpuAbisForSharedUserLPw(setting.packages, null, 1636 false /* force dexopt */, false /* defer dexopt */); 1637 } 1638 1639 // Now that we know all the packages we are keeping, 1640 // read and update their last usage times. 1641 mPackageUsage.readLP(); 1642 1643 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 1644 SystemClock.uptimeMillis()); 1645 Slog.i(TAG, "Time to scan packages: " 1646 + ((SystemClock.uptimeMillis()-startTime)/1000f) 1647 + " seconds"); 1648 1649 // If the platform SDK has changed since the last time we booted, 1650 // we need to re-grant app permission to catch any new ones that 1651 // appear. This is really a hack, and means that apps can in some 1652 // cases get permissions that the user didn't initially explicitly 1653 // allow... it would be nice to have some better way to handle 1654 // this situation. 1655 final boolean regrantPermissions = mSettings.mInternalSdkPlatform 1656 != mSdkVersion; 1657 if (regrantPermissions) Slog.i(TAG, "Platform changed from " 1658 + mSettings.mInternalSdkPlatform + " to " + mSdkVersion 1659 + "; regranting permissions for internal storage"); 1660 mSettings.mInternalSdkPlatform = mSdkVersion; 1661 1662 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 1663 | (regrantPermissions 1664 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 1665 : 0)); 1666 1667 // If this is the first boot, and it is a normal boot, then 1668 // we need to initialize the default preferred apps. 1669 if (!mRestoredSettings && !onlyCore) { 1670 mSettings.readDefaultPreferredAppsLPw(this, 0); 1671 } 1672 1673 // can downgrade to reader 1674 mSettings.writeLPr(); 1675 1676 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 1677 SystemClock.uptimeMillis()); 1678 1679 // Now after opening every single application zip, make sure they 1680 // are all flushed. Not really needed, but keeps things nice and 1681 // tidy. 1682 Runtime.getRuntime().gc(); 1683 1684 mRequiredVerifierPackage = getRequiredVerifierLPr(); 1685 } // synchronized (mPackages) 1686 } // synchronized (mInstallLock) 1687 } 1688 1689 @Override 1690 public boolean isFirstBoot() { 1691 return !mRestoredSettings; 1692 } 1693 1694 @Override 1695 public boolean isOnlyCoreApps() { 1696 return mOnlyCore; 1697 } 1698 1699 private String getRequiredVerifierLPr() { 1700 final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 1701 final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE, 1702 PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */); 1703 1704 String requiredVerifier = null; 1705 1706 final int N = receivers.size(); 1707 for (int i = 0; i < N; i++) { 1708 final ResolveInfo info = receivers.get(i); 1709 1710 if (info.activityInfo == null) { 1711 continue; 1712 } 1713 1714 final String packageName = info.activityInfo.packageName; 1715 1716 final PackageSetting ps = mSettings.mPackages.get(packageName); 1717 if (ps == null) { 1718 continue; 1719 } 1720 1721 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1722 if (!gp.grantedPermissions 1723 .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) { 1724 continue; 1725 } 1726 1727 if (requiredVerifier != null) { 1728 throw new RuntimeException("There can be only one required verifier"); 1729 } 1730 1731 requiredVerifier = packageName; 1732 } 1733 1734 return requiredVerifier; 1735 } 1736 1737 @Override 1738 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1739 throws RemoteException { 1740 try { 1741 return super.onTransact(code, data, reply, flags); 1742 } catch (RuntimeException e) { 1743 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 1744 Slog.wtf(TAG, "Package Manager Crash", e); 1745 } 1746 throw e; 1747 } 1748 } 1749 1750 void cleanupInstallFailedPackage(PackageSetting ps) { 1751 Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name); 1752 removeDataDirsLI(ps.name); 1753 if (ps.codePath != null) { 1754 if (!ps.codePath.delete()) { 1755 Slog.w(TAG, "Unable to remove old code file: " + ps.codePath); 1756 } 1757 } 1758 if (ps.resourcePath != null) { 1759 if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) { 1760 Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath); 1761 } 1762 } 1763 mSettings.removePackageLPw(ps.name); 1764 } 1765 1766 void readPermissions() { 1767 // Read permissions from .../etc/permission directory. 1768 File libraryDir = new File(Environment.getRootDirectory(), "etc/permissions"); 1769 if (!libraryDir.exists() || !libraryDir.isDirectory()) { 1770 Slog.w(TAG, "No directory " + libraryDir + ", skipping"); 1771 return; 1772 } 1773 if (!libraryDir.canRead()) { 1774 Slog.w(TAG, "Directory " + libraryDir + " cannot be read"); 1775 return; 1776 } 1777 1778 // Iterate over the files in the directory and scan .xml files 1779 for (File f : libraryDir.listFiles()) { 1780 // We'll read platform.xml last 1781 if (f.getPath().endsWith("etc/permissions/platform.xml")) { 1782 continue; 1783 } 1784 1785 if (!f.getPath().endsWith(".xml")) { 1786 Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring"); 1787 continue; 1788 } 1789 if (!f.canRead()) { 1790 Slog.w(TAG, "Permissions library file " + f + " cannot be read"); 1791 continue; 1792 } 1793 1794 readPermissionsFromXml(f); 1795 } 1796 1797 // Read permissions from .../etc/permissions/platform.xml last so it will take precedence 1798 final File permFile = new File(Environment.getRootDirectory(), 1799 "etc/permissions/platform.xml"); 1800 readPermissionsFromXml(permFile); 1801 } 1802 1803 private void readPermissionsFromXml(File permFile) { 1804 FileReader permReader = null; 1805 try { 1806 permReader = new FileReader(permFile); 1807 } catch (FileNotFoundException e) { 1808 Slog.w(TAG, "Couldn't find or open permissions file " + permFile); 1809 return; 1810 } 1811 1812 try { 1813 XmlPullParser parser = Xml.newPullParser(); 1814 parser.setInput(permReader); 1815 1816 XmlUtils.beginDocument(parser, "permissions"); 1817 1818 while (true) { 1819 XmlUtils.nextElement(parser); 1820 if (parser.getEventType() == XmlPullParser.END_DOCUMENT) { 1821 break; 1822 } 1823 1824 String name = parser.getName(); 1825 if ("group".equals(name)) { 1826 String gidStr = parser.getAttributeValue(null, "gid"); 1827 if (gidStr != null) { 1828 int gid = Process.getGidForName(gidStr); 1829 mGlobalGids = appendInt(mGlobalGids, gid); 1830 } else { 1831 Slog.w(TAG, "<group> without gid at " 1832 + parser.getPositionDescription()); 1833 } 1834 1835 XmlUtils.skipCurrentTag(parser); 1836 continue; 1837 } else if ("permission".equals(name)) { 1838 String perm = parser.getAttributeValue(null, "name"); 1839 if (perm == null) { 1840 Slog.w(TAG, "<permission> without name at " 1841 + parser.getPositionDescription()); 1842 XmlUtils.skipCurrentTag(parser); 1843 continue; 1844 } 1845 perm = perm.intern(); 1846 readPermission(parser, perm); 1847 1848 } else if ("assign-permission".equals(name)) { 1849 String perm = parser.getAttributeValue(null, "name"); 1850 if (perm == null) { 1851 Slog.w(TAG, "<assign-permission> without name at " 1852 + parser.getPositionDescription()); 1853 XmlUtils.skipCurrentTag(parser); 1854 continue; 1855 } 1856 String uidStr = parser.getAttributeValue(null, "uid"); 1857 if (uidStr == null) { 1858 Slog.w(TAG, "<assign-permission> without uid at " 1859 + parser.getPositionDescription()); 1860 XmlUtils.skipCurrentTag(parser); 1861 continue; 1862 } 1863 int uid = Process.getUidForName(uidStr); 1864 if (uid < 0) { 1865 Slog.w(TAG, "<assign-permission> with unknown uid \"" 1866 + uidStr + "\" at " 1867 + parser.getPositionDescription()); 1868 XmlUtils.skipCurrentTag(parser); 1869 continue; 1870 } 1871 perm = perm.intern(); 1872 HashSet<String> perms = mSystemPermissions.get(uid); 1873 if (perms == null) { 1874 perms = new HashSet<String>(); 1875 mSystemPermissions.put(uid, perms); 1876 } 1877 perms.add(perm); 1878 XmlUtils.skipCurrentTag(parser); 1879 1880 } else if ("library".equals(name)) { 1881 String lname = parser.getAttributeValue(null, "name"); 1882 String lfile = parser.getAttributeValue(null, "file"); 1883 if (lname == null) { 1884 Slog.w(TAG, "<library> without name at " 1885 + parser.getPositionDescription()); 1886 } else if (lfile == null) { 1887 Slog.w(TAG, "<library> without file at " 1888 + parser.getPositionDescription()); 1889 } else { 1890 //Log.i(TAG, "Got library " + lname + " in " + lfile); 1891 mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null)); 1892 } 1893 XmlUtils.skipCurrentTag(parser); 1894 continue; 1895 1896 } else if ("feature".equals(name)) { 1897 String fname = parser.getAttributeValue(null, "name"); 1898 if (fname == null) { 1899 Slog.w(TAG, "<feature> without name at " 1900 + parser.getPositionDescription()); 1901 } else { 1902 //Log.i(TAG, "Got feature " + fname); 1903 FeatureInfo fi = new FeatureInfo(); 1904 fi.name = fname; 1905 mAvailableFeatures.put(fname, fi); 1906 } 1907 XmlUtils.skipCurrentTag(parser); 1908 continue; 1909 1910 } else { 1911 XmlUtils.skipCurrentTag(parser); 1912 continue; 1913 } 1914 1915 } 1916 permReader.close(); 1917 } catch (XmlPullParserException e) { 1918 Slog.w(TAG, "Got execption parsing permissions.", e); 1919 } catch (IOException e) { 1920 Slog.w(TAG, "Got execption parsing permissions.", e); 1921 } 1922 } 1923 1924 void readPermission(XmlPullParser parser, String name) 1925 throws IOException, XmlPullParserException { 1926 1927 name = name.intern(); 1928 1929 BasePermission bp = mSettings.mPermissions.get(name); 1930 if (bp == null) { 1931 bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN); 1932 mSettings.mPermissions.put(name, bp); 1933 } 1934 int outerDepth = parser.getDepth(); 1935 int type; 1936 while ((type=parser.next()) != XmlPullParser.END_DOCUMENT 1937 && (type != XmlPullParser.END_TAG 1938 || parser.getDepth() > outerDepth)) { 1939 if (type == XmlPullParser.END_TAG 1940 || type == XmlPullParser.TEXT) { 1941 continue; 1942 } 1943 1944 String tagName = parser.getName(); 1945 if ("group".equals(tagName)) { 1946 String gidStr = parser.getAttributeValue(null, "gid"); 1947 if (gidStr != null) { 1948 int gid = Process.getGidForName(gidStr); 1949 bp.gids = appendInt(bp.gids, gid); 1950 } else { 1951 Slog.w(TAG, "<group> without gid at " 1952 + parser.getPositionDescription()); 1953 } 1954 } 1955 XmlUtils.skipCurrentTag(parser); 1956 } 1957 } 1958 1959 static int[] appendInts(int[] cur, int[] add) { 1960 if (add == null) return cur; 1961 if (cur == null) return add; 1962 final int N = add.length; 1963 for (int i=0; i<N; i++) { 1964 cur = appendInt(cur, add[i]); 1965 } 1966 return cur; 1967 } 1968 1969 static int[] removeInts(int[] cur, int[] rem) { 1970 if (rem == null) return cur; 1971 if (cur == null) return cur; 1972 final int N = rem.length; 1973 for (int i=0; i<N; i++) { 1974 cur = removeInt(cur, rem[i]); 1975 } 1976 return cur; 1977 } 1978 1979 PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) { 1980 if (!sUserManager.exists(userId)) return null; 1981 final PackageSetting ps = (PackageSetting) p.mExtras; 1982 if (ps == null) { 1983 return null; 1984 } 1985 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 1986 final PackageUserState state = ps.readUserState(userId); 1987 return PackageParser.generatePackageInfo(p, gp.gids, flags, 1988 ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions, 1989 state, userId); 1990 } 1991 1992 @Override 1993 public boolean isPackageAvailable(String packageName, int userId) { 1994 if (!sUserManager.exists(userId)) return false; 1995 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available"); 1996 synchronized (mPackages) { 1997 PackageParser.Package p = mPackages.get(packageName); 1998 if (p != null) { 1999 final PackageSetting ps = (PackageSetting) p.mExtras; 2000 if (ps != null) { 2001 final PackageUserState state = ps.readUserState(userId); 2002 if (state != null) { 2003 return PackageParser.isAvailable(state); 2004 } 2005 } 2006 } 2007 } 2008 return false; 2009 } 2010 2011 @Override 2012 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 2013 if (!sUserManager.exists(userId)) return null; 2014 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info"); 2015 // reader 2016 synchronized (mPackages) { 2017 PackageParser.Package p = mPackages.get(packageName); 2018 if (DEBUG_PACKAGE_INFO) 2019 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 2020 if (p != null) { 2021 return generatePackageInfo(p, flags, userId); 2022 } 2023 if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2024 return generatePackageInfoFromSettingsLPw(packageName, flags, userId); 2025 } 2026 } 2027 return null; 2028 } 2029 2030 @Override 2031 public String[] currentToCanonicalPackageNames(String[] names) { 2032 String[] out = new String[names.length]; 2033 // reader 2034 synchronized (mPackages) { 2035 for (int i=names.length-1; i>=0; i--) { 2036 PackageSetting ps = mSettings.mPackages.get(names[i]); 2037 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 2038 } 2039 } 2040 return out; 2041 } 2042 2043 @Override 2044 public String[] canonicalToCurrentPackageNames(String[] names) { 2045 String[] out = new String[names.length]; 2046 // reader 2047 synchronized (mPackages) { 2048 for (int i=names.length-1; i>=0; i--) { 2049 String cur = mSettings.mRenamedPackages.get(names[i]); 2050 out[i] = cur != null ? cur : names[i]; 2051 } 2052 } 2053 return out; 2054 } 2055 2056 @Override 2057 public int getPackageUid(String packageName, int userId) { 2058 if (!sUserManager.exists(userId)) return -1; 2059 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid"); 2060 // reader 2061 synchronized (mPackages) { 2062 PackageParser.Package p = mPackages.get(packageName); 2063 if(p != null) { 2064 return UserHandle.getUid(userId, p.applicationInfo.uid); 2065 } 2066 PackageSetting ps = mSettings.mPackages.get(packageName); 2067 if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) { 2068 return -1; 2069 } 2070 p = ps.pkg; 2071 return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1; 2072 } 2073 } 2074 2075 @Override 2076 public int[] getPackageGids(String packageName) { 2077 // reader 2078 synchronized (mPackages) { 2079 PackageParser.Package p = mPackages.get(packageName); 2080 if (DEBUG_PACKAGE_INFO) 2081 Log.v(TAG, "getPackageGids" + packageName + ": " + p); 2082 if (p != null) { 2083 final PackageSetting ps = (PackageSetting)p.mExtras; 2084 return ps.getGids(); 2085 } 2086 } 2087 // stupid thing to indicate an error. 2088 return new int[0]; 2089 } 2090 2091 static final PermissionInfo generatePermissionInfo( 2092 BasePermission bp, int flags) { 2093 if (bp.perm != null) { 2094 return PackageParser.generatePermissionInfo(bp.perm, flags); 2095 } 2096 PermissionInfo pi = new PermissionInfo(); 2097 pi.name = bp.name; 2098 pi.packageName = bp.sourcePackage; 2099 pi.nonLocalizedLabel = bp.name; 2100 pi.protectionLevel = bp.protectionLevel; 2101 return pi; 2102 } 2103 2104 @Override 2105 public PermissionInfo getPermissionInfo(String name, int flags) { 2106 // reader 2107 synchronized (mPackages) { 2108 final BasePermission p = mSettings.mPermissions.get(name); 2109 if (p != null) { 2110 return generatePermissionInfo(p, flags); 2111 } 2112 return null; 2113 } 2114 } 2115 2116 @Override 2117 public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) { 2118 // reader 2119 synchronized (mPackages) { 2120 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 2121 for (BasePermission p : mSettings.mPermissions.values()) { 2122 if (group == null) { 2123 if (p.perm == null || p.perm.info.group == null) { 2124 out.add(generatePermissionInfo(p, flags)); 2125 } 2126 } else { 2127 if (p.perm != null && group.equals(p.perm.info.group)) { 2128 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 2129 } 2130 } 2131 } 2132 2133 if (out.size() > 0) { 2134 return out; 2135 } 2136 return mPermissionGroups.containsKey(group) ? out : null; 2137 } 2138 } 2139 2140 @Override 2141 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 2142 // reader 2143 synchronized (mPackages) { 2144 return PackageParser.generatePermissionGroupInfo( 2145 mPermissionGroups.get(name), flags); 2146 } 2147 } 2148 2149 @Override 2150 public List<PermissionGroupInfo> getAllPermissionGroups(int flags) { 2151 // reader 2152 synchronized (mPackages) { 2153 final int N = mPermissionGroups.size(); 2154 ArrayList<PermissionGroupInfo> out 2155 = new ArrayList<PermissionGroupInfo>(N); 2156 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 2157 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 2158 } 2159 return out; 2160 } 2161 } 2162 2163 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 2164 int userId) { 2165 if (!sUserManager.exists(userId)) return null; 2166 PackageSetting ps = mSettings.mPackages.get(packageName); 2167 if (ps != null) { 2168 if (ps.pkg == null) { 2169 PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName, 2170 flags, userId); 2171 if (pInfo != null) { 2172 return pInfo.applicationInfo; 2173 } 2174 return null; 2175 } 2176 return PackageParser.generateApplicationInfo(ps.pkg, flags, 2177 ps.readUserState(userId), userId); 2178 } 2179 return null; 2180 } 2181 2182 private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags, 2183 int userId) { 2184 if (!sUserManager.exists(userId)) return null; 2185 PackageSetting ps = mSettings.mPackages.get(packageName); 2186 if (ps != null) { 2187 PackageParser.Package pkg = ps.pkg; 2188 if (pkg == null) { 2189 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) { 2190 return null; 2191 } 2192 pkg = new PackageParser.Package(packageName); 2193 pkg.applicationInfo.packageName = packageName; 2194 pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY; 2195 pkg.applicationInfo.publicSourceDir = ps.resourcePathString; 2196 pkg.applicationInfo.sourceDir = ps.codePathString; 2197 pkg.applicationInfo.dataDir = 2198 getDataPathForPackage(packageName, 0).getPath(); 2199 pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString; 2200 pkg.applicationInfo.cpuAbi = ps.cpuAbiString; 2201 } 2202 return generatePackageInfo(pkg, flags, userId); 2203 } 2204 return null; 2205 } 2206 2207 @Override 2208 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 2209 if (!sUserManager.exists(userId)) return null; 2210 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info"); 2211 // writer 2212 synchronized (mPackages) { 2213 PackageParser.Package p = mPackages.get(packageName); 2214 if (DEBUG_PACKAGE_INFO) Log.v( 2215 TAG, "getApplicationInfo " + packageName 2216 + ": " + p); 2217 if (p != null) { 2218 PackageSetting ps = mSettings.mPackages.get(packageName); 2219 if (ps == null) return null; 2220 // Note: isEnabledLP() does not apply here - always return info 2221 return PackageParser.generateApplicationInfo( 2222 p, flags, ps.readUserState(userId), userId); 2223 } 2224 if ("android".equals(packageName)||"system".equals(packageName)) { 2225 return mAndroidApplication; 2226 } 2227 if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) { 2228 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 2229 } 2230 } 2231 return null; 2232 } 2233 2234 2235 @Override 2236 public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) { 2237 mContext.enforceCallingOrSelfPermission( 2238 android.Manifest.permission.CLEAR_APP_CACHE, null); 2239 // Queue up an async operation since clearing cache may take a little while. 2240 mHandler.post(new Runnable() { 2241 public void run() { 2242 mHandler.removeCallbacks(this); 2243 int retCode = -1; 2244 synchronized (mInstallLock) { 2245 retCode = mInstaller.freeCache(freeStorageSize); 2246 if (retCode < 0) { 2247 Slog.w(TAG, "Couldn't clear application caches"); 2248 } 2249 } 2250 if (observer != null) { 2251 try { 2252 observer.onRemoveCompleted(null, (retCode >= 0)); 2253 } catch (RemoteException e) { 2254 Slog.w(TAG, "RemoveException when invoking call back"); 2255 } 2256 } 2257 } 2258 }); 2259 } 2260 2261 @Override 2262 public void freeStorage(final long freeStorageSize, final IntentSender pi) { 2263 mContext.enforceCallingOrSelfPermission( 2264 android.Manifest.permission.CLEAR_APP_CACHE, null); 2265 // Queue up an async operation since clearing cache may take a little while. 2266 mHandler.post(new Runnable() { 2267 public void run() { 2268 mHandler.removeCallbacks(this); 2269 int retCode = -1; 2270 synchronized (mInstallLock) { 2271 retCode = mInstaller.freeCache(freeStorageSize); 2272 if (retCode < 0) { 2273 Slog.w(TAG, "Couldn't clear application caches"); 2274 } 2275 } 2276 if(pi != null) { 2277 try { 2278 // Callback via pending intent 2279 int code = (retCode >= 0) ? 1 : 0; 2280 pi.sendIntent(null, code, null, 2281 null, null); 2282 } catch (SendIntentException e1) { 2283 Slog.i(TAG, "Failed to send pending intent"); 2284 } 2285 } 2286 } 2287 }); 2288 } 2289 2290 @Override 2291 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 2292 if (!sUserManager.exists(userId)) return null; 2293 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info"); 2294 synchronized (mPackages) { 2295 PackageParser.Activity a = mActivities.mActivities.get(component); 2296 2297 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 2298 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2299 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2300 if (ps == null) return null; 2301 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2302 userId); 2303 } 2304 if (mResolveComponentName.equals(component)) { 2305 return mResolveActivity; 2306 } 2307 } 2308 return null; 2309 } 2310 2311 @Override 2312 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 2313 if (!sUserManager.exists(userId)) return null; 2314 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info"); 2315 synchronized (mPackages) { 2316 PackageParser.Activity a = mReceivers.mActivities.get(component); 2317 if (DEBUG_PACKAGE_INFO) Log.v( 2318 TAG, "getReceiverInfo " + component + ": " + a); 2319 if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) { 2320 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2321 if (ps == null) return null; 2322 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 2323 userId); 2324 } 2325 } 2326 return null; 2327 } 2328 2329 @Override 2330 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 2331 if (!sUserManager.exists(userId)) return null; 2332 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info"); 2333 synchronized (mPackages) { 2334 PackageParser.Service s = mServices.mServices.get(component); 2335 if (DEBUG_PACKAGE_INFO) Log.v( 2336 TAG, "getServiceInfo " + component + ": " + s); 2337 if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) { 2338 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2339 if (ps == null) return null; 2340 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 2341 userId); 2342 } 2343 } 2344 return null; 2345 } 2346 2347 @Override 2348 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 2349 if (!sUserManager.exists(userId)) return null; 2350 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info"); 2351 synchronized (mPackages) { 2352 PackageParser.Provider p = mProviders.mProviders.get(component); 2353 if (DEBUG_PACKAGE_INFO) Log.v( 2354 TAG, "getProviderInfo " + component + ": " + p); 2355 if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) { 2356 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 2357 if (ps == null) return null; 2358 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 2359 userId); 2360 } 2361 } 2362 return null; 2363 } 2364 2365 @Override 2366 public String[] getSystemSharedLibraryNames() { 2367 Set<String> libSet; 2368 synchronized (mPackages) { 2369 libSet = mSharedLibraries.keySet(); 2370 int size = libSet.size(); 2371 if (size > 0) { 2372 String[] libs = new String[size]; 2373 libSet.toArray(libs); 2374 return libs; 2375 } 2376 } 2377 return null; 2378 } 2379 2380 @Override 2381 public FeatureInfo[] getSystemAvailableFeatures() { 2382 Collection<FeatureInfo> featSet; 2383 synchronized (mPackages) { 2384 featSet = mAvailableFeatures.values(); 2385 int size = featSet.size(); 2386 if (size > 0) { 2387 FeatureInfo[] features = new FeatureInfo[size+1]; 2388 featSet.toArray(features); 2389 FeatureInfo fi = new FeatureInfo(); 2390 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 2391 FeatureInfo.GL_ES_VERSION_UNDEFINED); 2392 features[size] = fi; 2393 return features; 2394 } 2395 } 2396 return null; 2397 } 2398 2399 @Override 2400 public boolean hasSystemFeature(String name) { 2401 synchronized (mPackages) { 2402 return mAvailableFeatures.containsKey(name); 2403 } 2404 } 2405 2406 private void checkValidCaller(int uid, int userId) { 2407 if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0) 2408 return; 2409 2410 throw new SecurityException("Caller uid=" + uid 2411 + " is not privileged to communicate with user=" + userId); 2412 } 2413 2414 @Override 2415 public int checkPermission(String permName, String pkgName) { 2416 synchronized (mPackages) { 2417 PackageParser.Package p = mPackages.get(pkgName); 2418 if (p != null && p.mExtras != null) { 2419 PackageSetting ps = (PackageSetting)p.mExtras; 2420 if (ps.sharedUser != null) { 2421 if (ps.sharedUser.grantedPermissions.contains(permName)) { 2422 return PackageManager.PERMISSION_GRANTED; 2423 } 2424 } else if (ps.grantedPermissions.contains(permName)) { 2425 return PackageManager.PERMISSION_GRANTED; 2426 } 2427 } 2428 } 2429 return PackageManager.PERMISSION_DENIED; 2430 } 2431 2432 @Override 2433 public int checkUidPermission(String permName, int uid) { 2434 synchronized (mPackages) { 2435 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2436 if (obj != null) { 2437 GrantedPermissions gp = (GrantedPermissions)obj; 2438 if (gp.grantedPermissions.contains(permName)) { 2439 return PackageManager.PERMISSION_GRANTED; 2440 } 2441 } else { 2442 HashSet<String> perms = mSystemPermissions.get(uid); 2443 if (perms != null && perms.contains(permName)) { 2444 return PackageManager.PERMISSION_GRANTED; 2445 } 2446 } 2447 } 2448 return PackageManager.PERMISSION_DENIED; 2449 } 2450 2451 /** 2452 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 2453 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 2454 * @param message the message to log on security exception 2455 * @return 2456 */ 2457 private void enforceCrossUserPermission(int callingUid, int userId, 2458 boolean requireFullPermission, String message) { 2459 if (userId < 0) { 2460 throw new IllegalArgumentException("Invalid userId " + userId); 2461 } 2462 if (userId == UserHandle.getUserId(callingUid)) return; 2463 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 2464 if (requireFullPermission) { 2465 mContext.enforceCallingOrSelfPermission( 2466 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2467 } else { 2468 try { 2469 mContext.enforceCallingOrSelfPermission( 2470 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 2471 } catch (SecurityException se) { 2472 mContext.enforceCallingOrSelfPermission( 2473 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 2474 } 2475 } 2476 } 2477 } 2478 2479 private BasePermission findPermissionTreeLP(String permName) { 2480 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 2481 if (permName.startsWith(bp.name) && 2482 permName.length() > bp.name.length() && 2483 permName.charAt(bp.name.length()) == '.') { 2484 return bp; 2485 } 2486 } 2487 return null; 2488 } 2489 2490 private BasePermission checkPermissionTreeLP(String permName) { 2491 if (permName != null) { 2492 BasePermission bp = findPermissionTreeLP(permName); 2493 if (bp != null) { 2494 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 2495 return bp; 2496 } 2497 throw new SecurityException("Calling uid " 2498 + Binder.getCallingUid() 2499 + " is not allowed to add to permission tree " 2500 + bp.name + " owned by uid " + bp.uid); 2501 } 2502 } 2503 throw new SecurityException("No permission tree found for " + permName); 2504 } 2505 2506 static boolean compareStrings(CharSequence s1, CharSequence s2) { 2507 if (s1 == null) { 2508 return s2 == null; 2509 } 2510 if (s2 == null) { 2511 return false; 2512 } 2513 if (s1.getClass() != s2.getClass()) { 2514 return false; 2515 } 2516 return s1.equals(s2); 2517 } 2518 2519 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 2520 if (pi1.icon != pi2.icon) return false; 2521 if (pi1.logo != pi2.logo) return false; 2522 if (pi1.protectionLevel != pi2.protectionLevel) return false; 2523 if (!compareStrings(pi1.name, pi2.name)) return false; 2524 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 2525 // We'll take care of setting this one. 2526 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 2527 // These are not currently stored in settings. 2528 //if (!compareStrings(pi1.group, pi2.group)) return false; 2529 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 2530 //if (pi1.labelRes != pi2.labelRes) return false; 2531 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 2532 return true; 2533 } 2534 2535 boolean addPermissionLocked(PermissionInfo info, boolean async) { 2536 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 2537 throw new SecurityException("Label must be specified in permission"); 2538 } 2539 BasePermission tree = checkPermissionTreeLP(info.name); 2540 BasePermission bp = mSettings.mPermissions.get(info.name); 2541 boolean added = bp == null; 2542 boolean changed = true; 2543 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 2544 if (added) { 2545 bp = new BasePermission(info.name, tree.sourcePackage, 2546 BasePermission.TYPE_DYNAMIC); 2547 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 2548 throw new SecurityException( 2549 "Not allowed to modify non-dynamic permission " 2550 + info.name); 2551 } else { 2552 if (bp.protectionLevel == fixedLevel 2553 && bp.perm.owner.equals(tree.perm.owner) 2554 && bp.uid == tree.uid 2555 && comparePermissionInfos(bp.perm.info, info)) { 2556 changed = false; 2557 } 2558 } 2559 bp.protectionLevel = fixedLevel; 2560 info = new PermissionInfo(info); 2561 info.protectionLevel = fixedLevel; 2562 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 2563 bp.perm.info.packageName = tree.perm.info.packageName; 2564 bp.uid = tree.uid; 2565 if (added) { 2566 mSettings.mPermissions.put(info.name, bp); 2567 } 2568 if (changed) { 2569 if (!async) { 2570 mSettings.writeLPr(); 2571 } else { 2572 scheduleWriteSettingsLocked(); 2573 } 2574 } 2575 return added; 2576 } 2577 2578 @Override 2579 public boolean addPermission(PermissionInfo info) { 2580 synchronized (mPackages) { 2581 return addPermissionLocked(info, false); 2582 } 2583 } 2584 2585 @Override 2586 public boolean addPermissionAsync(PermissionInfo info) { 2587 synchronized (mPackages) { 2588 return addPermissionLocked(info, true); 2589 } 2590 } 2591 2592 @Override 2593 public void removePermission(String name) { 2594 synchronized (mPackages) { 2595 checkPermissionTreeLP(name); 2596 BasePermission bp = mSettings.mPermissions.get(name); 2597 if (bp != null) { 2598 if (bp.type != BasePermission.TYPE_DYNAMIC) { 2599 throw new SecurityException( 2600 "Not allowed to modify non-dynamic permission " 2601 + name); 2602 } 2603 mSettings.mPermissions.remove(name); 2604 mSettings.writeLPr(); 2605 } 2606 } 2607 } 2608 2609 private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) { 2610 int index = pkg.requestedPermissions.indexOf(bp.name); 2611 if (index == -1) { 2612 throw new SecurityException("Package " + pkg.packageName 2613 + " has not requested permission " + bp.name); 2614 } 2615 boolean isNormal = 2616 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2617 == PermissionInfo.PROTECTION_NORMAL); 2618 boolean isDangerous = 2619 ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE) 2620 == PermissionInfo.PROTECTION_DANGEROUS); 2621 boolean isDevelopment = 2622 ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0); 2623 2624 if (!isNormal && !isDangerous && !isDevelopment) { 2625 throw new SecurityException("Permission " + bp.name 2626 + " is not a changeable permission type"); 2627 } 2628 2629 if (isNormal || isDangerous) { 2630 if (pkg.requestedPermissionsRequired.get(index)) { 2631 throw new SecurityException("Can't change " + bp.name 2632 + ". It is required by the application"); 2633 } 2634 } 2635 } 2636 2637 @Override 2638 public void grantPermission(String packageName, String permissionName) { 2639 mContext.enforceCallingOrSelfPermission( 2640 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2641 synchronized (mPackages) { 2642 final PackageParser.Package pkg = mPackages.get(packageName); 2643 if (pkg == null) { 2644 throw new IllegalArgumentException("Unknown package: " + packageName); 2645 } 2646 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2647 if (bp == null) { 2648 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2649 } 2650 2651 checkGrantRevokePermissions(pkg, bp); 2652 2653 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2654 if (ps == null) { 2655 return; 2656 } 2657 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2658 if (gp.grantedPermissions.add(permissionName)) { 2659 if (ps.haveGids) { 2660 gp.gids = appendInts(gp.gids, bp.gids); 2661 } 2662 mSettings.writeLPr(); 2663 } 2664 } 2665 } 2666 2667 @Override 2668 public void revokePermission(String packageName, String permissionName) { 2669 int changedAppId = -1; 2670 2671 synchronized (mPackages) { 2672 final PackageParser.Package pkg = mPackages.get(packageName); 2673 if (pkg == null) { 2674 throw new IllegalArgumentException("Unknown package: " + packageName); 2675 } 2676 if (pkg.applicationInfo.uid != Binder.getCallingUid()) { 2677 mContext.enforceCallingOrSelfPermission( 2678 android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null); 2679 } 2680 final BasePermission bp = mSettings.mPermissions.get(permissionName); 2681 if (bp == null) { 2682 throw new IllegalArgumentException("Unknown permission: " + permissionName); 2683 } 2684 2685 checkGrantRevokePermissions(pkg, bp); 2686 2687 final PackageSetting ps = (PackageSetting) pkg.mExtras; 2688 if (ps == null) { 2689 return; 2690 } 2691 final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps; 2692 if (gp.grantedPermissions.remove(permissionName)) { 2693 gp.grantedPermissions.remove(permissionName); 2694 if (ps.haveGids) { 2695 gp.gids = removeInts(gp.gids, bp.gids); 2696 } 2697 mSettings.writeLPr(); 2698 changedAppId = ps.appId; 2699 } 2700 } 2701 2702 if (changedAppId >= 0) { 2703 // We changed the perm on someone, kill its processes. 2704 IActivityManager am = ActivityManagerNative.getDefault(); 2705 if (am != null) { 2706 final int callingUserId = UserHandle.getCallingUserId(); 2707 final long ident = Binder.clearCallingIdentity(); 2708 try { 2709 //XXX we should only revoke for the calling user's app permissions, 2710 // but for now we impact all users. 2711 //am.killUid(UserHandle.getUid(callingUserId, changedAppId), 2712 // "revoke " + permissionName); 2713 int[] users = sUserManager.getUserIds(); 2714 for (int user : users) { 2715 am.killUid(UserHandle.getUid(user, changedAppId), 2716 "revoke " + permissionName); 2717 } 2718 } catch (RemoteException e) { 2719 } finally { 2720 Binder.restoreCallingIdentity(ident); 2721 } 2722 } 2723 } 2724 } 2725 2726 @Override 2727 public boolean isProtectedBroadcast(String actionName) { 2728 synchronized (mPackages) { 2729 return mProtectedBroadcasts.contains(actionName); 2730 } 2731 } 2732 2733 @Override 2734 public int checkSignatures(String pkg1, String pkg2) { 2735 synchronized (mPackages) { 2736 final PackageParser.Package p1 = mPackages.get(pkg1); 2737 final PackageParser.Package p2 = mPackages.get(pkg2); 2738 if (p1 == null || p1.mExtras == null 2739 || p2 == null || p2.mExtras == null) { 2740 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2741 } 2742 return compareSignatures(p1.mSignatures, p2.mSignatures); 2743 } 2744 } 2745 2746 @Override 2747 public int checkUidSignatures(int uid1, int uid2) { 2748 // Map to base uids. 2749 uid1 = UserHandle.getAppId(uid1); 2750 uid2 = UserHandle.getAppId(uid2); 2751 // reader 2752 synchronized (mPackages) { 2753 Signature[] s1; 2754 Signature[] s2; 2755 Object obj = mSettings.getUserIdLPr(uid1); 2756 if (obj != null) { 2757 if (obj instanceof SharedUserSetting) { 2758 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 2759 } else if (obj instanceof PackageSetting) { 2760 s1 = ((PackageSetting)obj).signatures.mSignatures; 2761 } else { 2762 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2763 } 2764 } else { 2765 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2766 } 2767 obj = mSettings.getUserIdLPr(uid2); 2768 if (obj != null) { 2769 if (obj instanceof SharedUserSetting) { 2770 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 2771 } else if (obj instanceof PackageSetting) { 2772 s2 = ((PackageSetting)obj).signatures.mSignatures; 2773 } else { 2774 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2775 } 2776 } else { 2777 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 2778 } 2779 return compareSignatures(s1, s2); 2780 } 2781 } 2782 2783 /** 2784 * Compares two sets of signatures. Returns: 2785 * <br /> 2786 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 2787 * <br /> 2788 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 2789 * <br /> 2790 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 2791 * <br /> 2792 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 2793 * <br /> 2794 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 2795 */ 2796 static int compareSignatures(Signature[] s1, Signature[] s2) { 2797 if (s1 == null) { 2798 return s2 == null 2799 ? PackageManager.SIGNATURE_NEITHER_SIGNED 2800 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 2801 } 2802 2803 if (s2 == null) { 2804 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 2805 } 2806 2807 if (s1.length != s2.length) { 2808 return PackageManager.SIGNATURE_NO_MATCH; 2809 } 2810 2811 // Since both signature sets are of size 1, we can compare without HashSets. 2812 if (s1.length == 1) { 2813 return s1[0].equals(s2[0]) ? 2814 PackageManager.SIGNATURE_MATCH : 2815 PackageManager.SIGNATURE_NO_MATCH; 2816 } 2817 2818 HashSet<Signature> set1 = new HashSet<Signature>(); 2819 for (Signature sig : s1) { 2820 set1.add(sig); 2821 } 2822 HashSet<Signature> set2 = new HashSet<Signature>(); 2823 for (Signature sig : s2) { 2824 set2.add(sig); 2825 } 2826 // Make sure s2 contains all signatures in s1. 2827 if (set1.equals(set2)) { 2828 return PackageManager.SIGNATURE_MATCH; 2829 } 2830 return PackageManager.SIGNATURE_NO_MATCH; 2831 } 2832 2833 @Override 2834 public String[] getPackagesForUid(int uid) { 2835 uid = UserHandle.getAppId(uid); 2836 // reader 2837 synchronized (mPackages) { 2838 Object obj = mSettings.getUserIdLPr(uid); 2839 if (obj instanceof SharedUserSetting) { 2840 final SharedUserSetting sus = (SharedUserSetting) obj; 2841 final int N = sus.packages.size(); 2842 final String[] res = new String[N]; 2843 final Iterator<PackageSetting> it = sus.packages.iterator(); 2844 int i = 0; 2845 while (it.hasNext()) { 2846 res[i++] = it.next().name; 2847 } 2848 return res; 2849 } else if (obj instanceof PackageSetting) { 2850 final PackageSetting ps = (PackageSetting) obj; 2851 return new String[] { ps.name }; 2852 } 2853 } 2854 return null; 2855 } 2856 2857 @Override 2858 public String getNameForUid(int uid) { 2859 // reader 2860 synchronized (mPackages) { 2861 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2862 if (obj instanceof SharedUserSetting) { 2863 final SharedUserSetting sus = (SharedUserSetting) obj; 2864 return sus.name + ":" + sus.userId; 2865 } else if (obj instanceof PackageSetting) { 2866 final PackageSetting ps = (PackageSetting) obj; 2867 return ps.name; 2868 } 2869 } 2870 return null; 2871 } 2872 2873 @Override 2874 public int getUidForSharedUser(String sharedUserName) { 2875 if(sharedUserName == null) { 2876 return -1; 2877 } 2878 // reader 2879 synchronized (mPackages) { 2880 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false); 2881 if (suid == null) { 2882 return -1; 2883 } 2884 return suid.userId; 2885 } 2886 } 2887 2888 @Override 2889 public int getFlagsForUid(int uid) { 2890 synchronized (mPackages) { 2891 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 2892 if (obj instanceof SharedUserSetting) { 2893 final SharedUserSetting sus = (SharedUserSetting) obj; 2894 return sus.pkgFlags; 2895 } else if (obj instanceof PackageSetting) { 2896 final PackageSetting ps = (PackageSetting) obj; 2897 return ps.pkgFlags; 2898 } 2899 } 2900 return 0; 2901 } 2902 2903 @Override 2904 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 2905 int flags, int userId) { 2906 if (!sUserManager.exists(userId)) return null; 2907 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent"); 2908 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2909 return chooseBestActivity(intent, resolvedType, flags, query, userId); 2910 } 2911 2912 @Override 2913 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 2914 IntentFilter filter, int match, ComponentName activity) { 2915 final int userId = UserHandle.getCallingUserId(); 2916 if (DEBUG_PREFERRED) { 2917 Log.v(TAG, "setLastChosenActivity intent=" + intent 2918 + " resolvedType=" + resolvedType 2919 + " flags=" + flags 2920 + " filter=" + filter 2921 + " match=" + match 2922 + " activity=" + activity); 2923 filter.dump(new PrintStreamPrinter(System.out), " "); 2924 } 2925 intent.setComponent(null); 2926 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2927 // Find any earlier preferred or last chosen entries and nuke them 2928 findPreferredActivity(intent, resolvedType, 2929 flags, query, 0, false, true, false, userId); 2930 // Add the new activity as the last chosen for this filter 2931 addPreferredActivityInternal(filter, match, null, activity, false, userId); 2932 } 2933 2934 @Override 2935 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 2936 final int userId = UserHandle.getCallingUserId(); 2937 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 2938 List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); 2939 return findPreferredActivity(intent, resolvedType, flags, query, 0, 2940 false, false, false, userId); 2941 } 2942 2943 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 2944 int flags, List<ResolveInfo> query, int userId) { 2945 if (query != null) { 2946 final int N = query.size(); 2947 if (N == 1) { 2948 return query.get(0); 2949 } else if (N > 1) { 2950 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 2951 // If there is more than one activity with the same priority, 2952 // then let the user decide between them. 2953 ResolveInfo r0 = query.get(0); 2954 ResolveInfo r1 = query.get(1); 2955 if (DEBUG_INTENT_MATCHING || debug) { 2956 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 2957 + r1.activityInfo.name + "=" + r1.priority); 2958 } 2959 // If the first activity has a higher priority, or a different 2960 // default, then it is always desireable to pick it. 2961 if (r0.priority != r1.priority 2962 || r0.preferredOrder != r1.preferredOrder 2963 || r0.isDefault != r1.isDefault) { 2964 return query.get(0); 2965 } 2966 // If we have saved a preference for a preferred activity for 2967 // this Intent, use that. 2968 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 2969 flags, query, r0.priority, true, false, debug, userId); 2970 if (ri != null) { 2971 return ri; 2972 } 2973 if (userId != 0) { 2974 ri = new ResolveInfo(mResolveInfo); 2975 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2976 ri.activityInfo.applicationInfo = new ApplicationInfo( 2977 ri.activityInfo.applicationInfo); 2978 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2979 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2980 return ri; 2981 } 2982 return mResolveInfo; 2983 } 2984 } 2985 return null; 2986 } 2987 2988 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 2989 List<ResolveInfo> query, int priority, boolean always, 2990 boolean removeMatches, boolean debug, int userId) { 2991 if (!sUserManager.exists(userId)) return null; 2992 // writer 2993 synchronized (mPackages) { 2994 if (intent.getSelector() != null) { 2995 intent = intent.getSelector(); 2996 } 2997 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 2998 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 2999 // Get the list of preferred activities that handle the intent 3000 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3001 List<PreferredActivity> prefs = pir != null 3002 ? pir.queryIntent(intent, resolvedType, 3003 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 3004 : null; 3005 if (prefs != null && prefs.size() > 0) { 3006 // First figure out how good the original match set is. 3007 // We will only allow preferred activities that came 3008 // from the same match quality. 3009 int match = 0; 3010 3011 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 3012 3013 final int N = query.size(); 3014 for (int j=0; j<N; j++) { 3015 final ResolveInfo ri = query.get(j); 3016 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 3017 + ": 0x" + Integer.toHexString(match)); 3018 if (ri.match > match) { 3019 match = ri.match; 3020 } 3021 } 3022 3023 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 3024 + Integer.toHexString(match)); 3025 3026 match &= IntentFilter.MATCH_CATEGORY_MASK; 3027 final int M = prefs.size(); 3028 for (int i=0; i<M; i++) { 3029 final PreferredActivity pa = prefs.get(i); 3030 if (DEBUG_PREFERRED || debug) { 3031 Slog.v(TAG, "Checking PreferredActivity ds=" 3032 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3033 + "\n component=" + pa.mPref.mComponent); 3034 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3035 } 3036 if (pa.mPref.mMatch != match) { 3037 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 3038 + Integer.toHexString(pa.mPref.mMatch)); 3039 continue; 3040 } 3041 // If it's not an "always" type preferred activity and that's what we're 3042 // looking for, skip it. 3043 if (always && !pa.mPref.mAlways) { 3044 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3045 continue; 3046 } 3047 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, 3048 flags | PackageManager.GET_DISABLED_COMPONENTS, userId); 3049 if (DEBUG_PREFERRED || debug) { 3050 Slog.v(TAG, "Found preferred activity:"); 3051 if (ai != null) { 3052 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3053 } else { 3054 Slog.v(TAG, " null"); 3055 } 3056 } 3057 if (ai == null) { 3058 // This previously registered preferred activity 3059 // component is no longer known. Most likely an update 3060 // to the app was installed and in the new version this 3061 // component no longer exists. Clean it up by removing 3062 // it from the preferred activities list, and skip it. 3063 Slog.w(TAG, "Removing dangling preferred activity: " 3064 + pa.mPref.mComponent); 3065 pir.removeFilter(pa); 3066 continue; 3067 } 3068 for (int j=0; j<N; j++) { 3069 final ResolveInfo ri = query.get(j); 3070 if (!ri.activityInfo.applicationInfo.packageName 3071 .equals(ai.applicationInfo.packageName)) { 3072 continue; 3073 } 3074 if (!ri.activityInfo.name.equals(ai.name)) { 3075 continue; 3076 } 3077 3078 if (removeMatches) { 3079 pir.removeFilter(pa); 3080 if (DEBUG_PREFERRED) { 3081 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3082 } 3083 break; 3084 } 3085 3086 // Okay we found a previously set preferred or last chosen app. 3087 // If the result set is different from when this 3088 // was created, we need to clear it and re-ask the 3089 // user their preference, if we're looking for an "always" type entry. 3090 if (always && !pa.mPref.sameSet(query, priority)) { 3091 Slog.i(TAG, "Result set changed, dropping preferred activity for " 3092 + intent + " type " + resolvedType); 3093 if (DEBUG_PREFERRED) { 3094 Slog.v(TAG, "Removing preferred activity since set changed " 3095 + pa.mPref.mComponent); 3096 } 3097 pir.removeFilter(pa); 3098 // Re-add the filter as a "last chosen" entry (!always) 3099 PreferredActivity lastChosen = new PreferredActivity( 3100 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 3101 pir.addFilter(lastChosen); 3102 mSettings.writePackageRestrictionsLPr(userId); 3103 return null; 3104 } 3105 3106 // Yay! Either the set matched or we're looking for the last chosen 3107 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 3108 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3109 mSettings.writePackageRestrictionsLPr(userId); 3110 return ri; 3111 } 3112 } 3113 } 3114 mSettings.writePackageRestrictionsLPr(userId); 3115 } 3116 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 3117 return null; 3118 } 3119 3120 @Override 3121 public List<ResolveInfo> queryIntentActivities(Intent intent, 3122 String resolvedType, int flags, int userId) { 3123 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3124 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 3125 ComponentName comp = intent.getComponent(); 3126 if (comp == null) { 3127 if (intent.getSelector() != null) { 3128 intent = intent.getSelector(); 3129 comp = intent.getComponent(); 3130 } 3131 } 3132 3133 if (comp != null) { 3134 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3135 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 3136 if (ai != null) { 3137 final ResolveInfo ri = new ResolveInfo(); 3138 ri.activityInfo = ai; 3139 list.add(ri); 3140 } 3141 return list; 3142 } 3143 3144 // reader 3145 synchronized (mPackages) { 3146 final String pkgName = intent.getPackage(); 3147 if (pkgName == null) { 3148 return mActivities.queryIntent(intent, resolvedType, flags, userId); 3149 } 3150 final PackageParser.Package pkg = mPackages.get(pkgName); 3151 if (pkg != null) { 3152 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 3153 pkg.activities, userId); 3154 } 3155 return new ArrayList<ResolveInfo>(); 3156 } 3157 } 3158 3159 @Override 3160 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 3161 Intent[] specifics, String[] specificTypes, Intent intent, 3162 String resolvedType, int flags, int userId) { 3163 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3164 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 3165 "query intent activity options"); 3166 final String resultsAction = intent.getAction(); 3167 3168 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 3169 | PackageManager.GET_RESOLVED_FILTER, userId); 3170 3171 if (DEBUG_INTENT_MATCHING) { 3172 Log.v(TAG, "Query " + intent + ": " + results); 3173 } 3174 3175 int specificsPos = 0; 3176 int N; 3177 3178 // todo: note that the algorithm used here is O(N^2). This 3179 // isn't a problem in our current environment, but if we start running 3180 // into situations where we have more than 5 or 10 matches then this 3181 // should probably be changed to something smarter... 3182 3183 // First we go through and resolve each of the specific items 3184 // that were supplied, taking care of removing any corresponding 3185 // duplicate items in the generic resolve list. 3186 if (specifics != null) { 3187 for (int i=0; i<specifics.length; i++) { 3188 final Intent sintent = specifics[i]; 3189 if (sintent == null) { 3190 continue; 3191 } 3192 3193 if (DEBUG_INTENT_MATCHING) { 3194 Log.v(TAG, "Specific #" + i + ": " + sintent); 3195 } 3196 3197 String action = sintent.getAction(); 3198 if (resultsAction != null && resultsAction.equals(action)) { 3199 // If this action was explicitly requested, then don't 3200 // remove things that have it. 3201 action = null; 3202 } 3203 3204 ResolveInfo ri = null; 3205 ActivityInfo ai = null; 3206 3207 ComponentName comp = sintent.getComponent(); 3208 if (comp == null) { 3209 ri = resolveIntent( 3210 sintent, 3211 specificTypes != null ? specificTypes[i] : null, 3212 flags, userId); 3213 if (ri == null) { 3214 continue; 3215 } 3216 if (ri == mResolveInfo) { 3217 // ACK! Must do something better with this. 3218 } 3219 ai = ri.activityInfo; 3220 comp = new ComponentName(ai.applicationInfo.packageName, 3221 ai.name); 3222 } else { 3223 ai = getActivityInfo(comp, flags, userId); 3224 if (ai == null) { 3225 continue; 3226 } 3227 } 3228 3229 // Look for any generic query activities that are duplicates 3230 // of this specific one, and remove them from the results. 3231 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 3232 N = results.size(); 3233 int j; 3234 for (j=specificsPos; j<N; j++) { 3235 ResolveInfo sri = results.get(j); 3236 if ((sri.activityInfo.name.equals(comp.getClassName()) 3237 && sri.activityInfo.applicationInfo.packageName.equals( 3238 comp.getPackageName())) 3239 || (action != null && sri.filter.matchAction(action))) { 3240 results.remove(j); 3241 if (DEBUG_INTENT_MATCHING) Log.v( 3242 TAG, "Removing duplicate item from " + j 3243 + " due to specific " + specificsPos); 3244 if (ri == null) { 3245 ri = sri; 3246 } 3247 j--; 3248 N--; 3249 } 3250 } 3251 3252 // Add this specific item to its proper place. 3253 if (ri == null) { 3254 ri = new ResolveInfo(); 3255 ri.activityInfo = ai; 3256 } 3257 results.add(specificsPos, ri); 3258 ri.specificIndex = i; 3259 specificsPos++; 3260 } 3261 } 3262 3263 // Now we go through the remaining generic results and remove any 3264 // duplicate actions that are found here. 3265 N = results.size(); 3266 for (int i=specificsPos; i<N-1; i++) { 3267 final ResolveInfo rii = results.get(i); 3268 if (rii.filter == null) { 3269 continue; 3270 } 3271 3272 // Iterate over all of the actions of this result's intent 3273 // filter... typically this should be just one. 3274 final Iterator<String> it = rii.filter.actionsIterator(); 3275 if (it == null) { 3276 continue; 3277 } 3278 while (it.hasNext()) { 3279 final String action = it.next(); 3280 if (resultsAction != null && resultsAction.equals(action)) { 3281 // If this action was explicitly requested, then don't 3282 // remove things that have it. 3283 continue; 3284 } 3285 for (int j=i+1; j<N; j++) { 3286 final ResolveInfo rij = results.get(j); 3287 if (rij.filter != null && rij.filter.hasAction(action)) { 3288 results.remove(j); 3289 if (DEBUG_INTENT_MATCHING) Log.v( 3290 TAG, "Removing duplicate item from " + j 3291 + " due to action " + action + " at " + i); 3292 j--; 3293 N--; 3294 } 3295 } 3296 } 3297 3298 // If the caller didn't request filter information, drop it now 3299 // so we don't have to marshall/unmarshall it. 3300 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3301 rii.filter = null; 3302 } 3303 } 3304 3305 // Filter out the caller activity if so requested. 3306 if (caller != null) { 3307 N = results.size(); 3308 for (int i=0; i<N; i++) { 3309 ActivityInfo ainfo = results.get(i).activityInfo; 3310 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 3311 && caller.getClassName().equals(ainfo.name)) { 3312 results.remove(i); 3313 break; 3314 } 3315 } 3316 } 3317 3318 // If the caller didn't request filter information, 3319 // drop them now so we don't have to 3320 // marshall/unmarshall it. 3321 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 3322 N = results.size(); 3323 for (int i=0; i<N; i++) { 3324 results.get(i).filter = null; 3325 } 3326 } 3327 3328 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 3329 return results; 3330 } 3331 3332 @Override 3333 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 3334 int userId) { 3335 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3336 ComponentName comp = intent.getComponent(); 3337 if (comp == null) { 3338 if (intent.getSelector() != null) { 3339 intent = intent.getSelector(); 3340 comp = intent.getComponent(); 3341 } 3342 } 3343 if (comp != null) { 3344 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3345 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 3346 if (ai != null) { 3347 ResolveInfo ri = new ResolveInfo(); 3348 ri.activityInfo = ai; 3349 list.add(ri); 3350 } 3351 return list; 3352 } 3353 3354 // reader 3355 synchronized (mPackages) { 3356 String pkgName = intent.getPackage(); 3357 if (pkgName == null) { 3358 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 3359 } 3360 final PackageParser.Package pkg = mPackages.get(pkgName); 3361 if (pkg != null) { 3362 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 3363 userId); 3364 } 3365 return null; 3366 } 3367 } 3368 3369 @Override 3370 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 3371 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 3372 if (!sUserManager.exists(userId)) return null; 3373 if (query != null) { 3374 if (query.size() >= 1) { 3375 // If there is more than one service with the same priority, 3376 // just arbitrarily pick the first one. 3377 return query.get(0); 3378 } 3379 } 3380 return null; 3381 } 3382 3383 @Override 3384 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 3385 int userId) { 3386 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3387 ComponentName comp = intent.getComponent(); 3388 if (comp == null) { 3389 if (intent.getSelector() != null) { 3390 intent = intent.getSelector(); 3391 comp = intent.getComponent(); 3392 } 3393 } 3394 if (comp != null) { 3395 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3396 final ServiceInfo si = getServiceInfo(comp, flags, userId); 3397 if (si != null) { 3398 final ResolveInfo ri = new ResolveInfo(); 3399 ri.serviceInfo = si; 3400 list.add(ri); 3401 } 3402 return list; 3403 } 3404 3405 // reader 3406 synchronized (mPackages) { 3407 String pkgName = intent.getPackage(); 3408 if (pkgName == null) { 3409 return mServices.queryIntent(intent, resolvedType, flags, userId); 3410 } 3411 final PackageParser.Package pkg = mPackages.get(pkgName); 3412 if (pkg != null) { 3413 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 3414 userId); 3415 } 3416 return null; 3417 } 3418 } 3419 3420 @Override 3421 public List<ResolveInfo> queryIntentContentProviders( 3422 Intent intent, String resolvedType, int flags, int userId) { 3423 if (!sUserManager.exists(userId)) return Collections.emptyList(); 3424 ComponentName comp = intent.getComponent(); 3425 if (comp == null) { 3426 if (intent.getSelector() != null) { 3427 intent = intent.getSelector(); 3428 comp = intent.getComponent(); 3429 } 3430 } 3431 if (comp != null) { 3432 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 3433 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 3434 if (pi != null) { 3435 final ResolveInfo ri = new ResolveInfo(); 3436 ri.providerInfo = pi; 3437 list.add(ri); 3438 } 3439 return list; 3440 } 3441 3442 // reader 3443 synchronized (mPackages) { 3444 String pkgName = intent.getPackage(); 3445 if (pkgName == null) { 3446 return mProviders.queryIntent(intent, resolvedType, flags, userId); 3447 } 3448 final PackageParser.Package pkg = mPackages.get(pkgName); 3449 if (pkg != null) { 3450 return mProviders.queryIntentForPackage( 3451 intent, resolvedType, flags, pkg.providers, userId); 3452 } 3453 return null; 3454 } 3455 } 3456 3457 @Override 3458 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 3459 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3460 3461 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 3462 3463 // writer 3464 synchronized (mPackages) { 3465 ArrayList<PackageInfo> list; 3466 if (listUninstalled) { 3467 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 3468 for (PackageSetting ps : mSettings.mPackages.values()) { 3469 PackageInfo pi; 3470 if (ps.pkg != null) { 3471 pi = generatePackageInfo(ps.pkg, flags, userId); 3472 } else { 3473 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3474 } 3475 if (pi != null) { 3476 list.add(pi); 3477 } 3478 } 3479 } else { 3480 list = new ArrayList<PackageInfo>(mPackages.size()); 3481 for (PackageParser.Package p : mPackages.values()) { 3482 PackageInfo pi = generatePackageInfo(p, flags, userId); 3483 if (pi != null) { 3484 list.add(pi); 3485 } 3486 } 3487 } 3488 3489 return new ParceledListSlice<PackageInfo>(list); 3490 } 3491 } 3492 3493 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 3494 String[] permissions, boolean[] tmp, int flags, int userId) { 3495 int numMatch = 0; 3496 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 3497 for (int i=0; i<permissions.length; i++) { 3498 if (gp.grantedPermissions.contains(permissions[i])) { 3499 tmp[i] = true; 3500 numMatch++; 3501 } else { 3502 tmp[i] = false; 3503 } 3504 } 3505 if (numMatch == 0) { 3506 return; 3507 } 3508 PackageInfo pi; 3509 if (ps.pkg != null) { 3510 pi = generatePackageInfo(ps.pkg, flags, userId); 3511 } else { 3512 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 3513 } 3514 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 3515 if (numMatch == permissions.length) { 3516 pi.requestedPermissions = permissions; 3517 } else { 3518 pi.requestedPermissions = new String[numMatch]; 3519 numMatch = 0; 3520 for (int i=0; i<permissions.length; i++) { 3521 if (tmp[i]) { 3522 pi.requestedPermissions[numMatch] = permissions[i]; 3523 numMatch++; 3524 } 3525 } 3526 } 3527 } 3528 list.add(pi); 3529 } 3530 3531 @Override 3532 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 3533 String[] permissions, int flags, int userId) { 3534 if (!sUserManager.exists(userId)) return null; 3535 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3536 3537 // writer 3538 synchronized (mPackages) { 3539 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 3540 boolean[] tmpBools = new boolean[permissions.length]; 3541 if (listUninstalled) { 3542 for (PackageSetting ps : mSettings.mPackages.values()) { 3543 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 3544 } 3545 } else { 3546 for (PackageParser.Package pkg : mPackages.values()) { 3547 PackageSetting ps = (PackageSetting)pkg.mExtras; 3548 if (ps != null) { 3549 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 3550 userId); 3551 } 3552 } 3553 } 3554 3555 return new ParceledListSlice<PackageInfo>(list); 3556 } 3557 } 3558 3559 @Override 3560 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 3561 if (!sUserManager.exists(userId)) return null; 3562 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 3563 3564 // writer 3565 synchronized (mPackages) { 3566 ArrayList<ApplicationInfo> list; 3567 if (listUninstalled) { 3568 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 3569 for (PackageSetting ps : mSettings.mPackages.values()) { 3570 ApplicationInfo ai; 3571 if (ps.pkg != null) { 3572 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3573 ps.readUserState(userId), userId); 3574 } else { 3575 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 3576 } 3577 if (ai != null) { 3578 list.add(ai); 3579 } 3580 } 3581 } else { 3582 list = new ArrayList<ApplicationInfo>(mPackages.size()); 3583 for (PackageParser.Package p : mPackages.values()) { 3584 if (p.mExtras != null) { 3585 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3586 ((PackageSetting)p.mExtras).readUserState(userId), userId); 3587 if (ai != null) { 3588 list.add(ai); 3589 } 3590 } 3591 } 3592 } 3593 3594 return new ParceledListSlice<ApplicationInfo>(list); 3595 } 3596 } 3597 3598 public List<ApplicationInfo> getPersistentApplications(int flags) { 3599 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3600 3601 // reader 3602 synchronized (mPackages) { 3603 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3604 final int userId = UserHandle.getCallingUserId(); 3605 while (i.hasNext()) { 3606 final PackageParser.Package p = i.next(); 3607 if (p.applicationInfo != null 3608 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3609 && (!mSafeMode || isSystemApp(p))) { 3610 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3611 if (ps != null) { 3612 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3613 ps.readUserState(userId), userId); 3614 if (ai != null) { 3615 finalList.add(ai); 3616 } 3617 } 3618 } 3619 } 3620 } 3621 3622 return finalList; 3623 } 3624 3625 @Override 3626 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3627 if (!sUserManager.exists(userId)) return null; 3628 // reader 3629 synchronized (mPackages) { 3630 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 3631 PackageSetting ps = provider != null 3632 ? mSettings.mPackages.get(provider.owner.packageName) 3633 : null; 3634 return ps != null 3635 && mSettings.isEnabledLPr(provider.info, flags, userId) 3636 && (!mSafeMode || (provider.info.applicationInfo.flags 3637 &ApplicationInfo.FLAG_SYSTEM) != 0) 3638 ? PackageParser.generateProviderInfo(provider, flags, 3639 ps.readUserState(userId), userId) 3640 : null; 3641 } 3642 } 3643 3644 /** 3645 * @deprecated 3646 */ 3647 @Deprecated 3648 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3649 // reader 3650 synchronized (mPackages) { 3651 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 3652 .entrySet().iterator(); 3653 final int userId = UserHandle.getCallingUserId(); 3654 while (i.hasNext()) { 3655 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3656 PackageParser.Provider p = entry.getValue(); 3657 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3658 3659 if (ps != null && p.syncable 3660 && (!mSafeMode || (p.info.applicationInfo.flags 3661 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3662 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3663 ps.readUserState(userId), userId); 3664 if (info != null) { 3665 outNames.add(entry.getKey()); 3666 outInfo.add(info); 3667 } 3668 } 3669 } 3670 } 3671 } 3672 3673 @Override 3674 public List<ProviderInfo> queryContentProviders(String processName, 3675 int uid, int flags) { 3676 ArrayList<ProviderInfo> finalList = null; 3677 // reader 3678 synchronized (mPackages) { 3679 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 3680 final int userId = processName != null ? 3681 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3682 while (i.hasNext()) { 3683 final PackageParser.Provider p = i.next(); 3684 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3685 if (ps != null && p.info.authority != null 3686 && (processName == null 3687 || (p.info.processName.equals(processName) 3688 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3689 && mSettings.isEnabledLPr(p.info, flags, userId) 3690 && (!mSafeMode 3691 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3692 if (finalList == null) { 3693 finalList = new ArrayList<ProviderInfo>(3); 3694 } 3695 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3696 ps.readUserState(userId), userId); 3697 if (info != null) { 3698 finalList.add(info); 3699 } 3700 } 3701 } 3702 } 3703 3704 if (finalList != null) { 3705 Collections.sort(finalList, mProviderInitOrderSorter); 3706 } 3707 3708 return finalList; 3709 } 3710 3711 @Override 3712 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3713 int flags) { 3714 // reader 3715 synchronized (mPackages) { 3716 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3717 return PackageParser.generateInstrumentationInfo(i, flags); 3718 } 3719 } 3720 3721 @Override 3722 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3723 int flags) { 3724 ArrayList<InstrumentationInfo> finalList = 3725 new ArrayList<InstrumentationInfo>(); 3726 3727 // reader 3728 synchronized (mPackages) { 3729 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3730 while (i.hasNext()) { 3731 final PackageParser.Instrumentation p = i.next(); 3732 if (targetPackage == null 3733 || targetPackage.equals(p.info.targetPackage)) { 3734 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3735 flags); 3736 if (ii != null) { 3737 finalList.add(ii); 3738 } 3739 } 3740 } 3741 } 3742 3743 return finalList; 3744 } 3745 3746 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 3747 HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 3748 if (overlays == null) { 3749 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 3750 return; 3751 } 3752 for (PackageParser.Package opkg : overlays.values()) { 3753 // Not much to do if idmap fails: we already logged the error 3754 // and we certainly don't want to abort installation of pkg simply 3755 // because an overlay didn't fit properly. For these reasons, 3756 // ignore the return value of createIdmapForPackagePairLI. 3757 createIdmapForPackagePairLI(pkg, opkg); 3758 } 3759 } 3760 3761 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 3762 PackageParser.Package opkg) { 3763 if (!opkg.mTrustedOverlay) { 3764 Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " + 3765 opkg.mScanPath + ": overlay not trusted"); 3766 return false; 3767 } 3768 HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 3769 if (overlaySet == null) { 3770 Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " + 3771 opkg.mScanPath + " but target package has no known overlays"); 3772 return false; 3773 } 3774 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3775 if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) { 3776 Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath); 3777 return false; 3778 } 3779 PackageParser.Package[] overlayArray = 3780 overlaySet.values().toArray(new PackageParser.Package[0]); 3781 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 3782 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 3783 return p1.mOverlayPriority - p2.mOverlayPriority; 3784 } 3785 }; 3786 Arrays.sort(overlayArray, cmp); 3787 3788 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 3789 int i = 0; 3790 for (PackageParser.Package p : overlayArray) { 3791 pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir; 3792 } 3793 return true; 3794 } 3795 3796 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3797 String[] files = dir.list(); 3798 if (files == null) { 3799 Log.d(TAG, "No files in app dir " + dir); 3800 return; 3801 } 3802 3803 if (DEBUG_PACKAGE_SCANNING) { 3804 Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode 3805 + " flags=0x" + Integer.toHexString(flags)); 3806 } 3807 3808 int i; 3809 for (i=0; i<files.length; i++) { 3810 File file = new File(dir, files[i]); 3811 if (!isPackageFilename(files[i])) { 3812 // Ignore entries which are not apk's 3813 continue; 3814 } 3815 PackageParser.Package pkg = scanPackageLI(file, 3816 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null); 3817 // Don't mess around with apps in system partition. 3818 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3819 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3820 // Delete the apk 3821 Slog.w(TAG, "Cleaning up failed install of " + file); 3822 file.delete(); 3823 } 3824 } 3825 } 3826 3827 private static File getSettingsProblemFile() { 3828 File dataDir = Environment.getDataDirectory(); 3829 File systemDir = new File(dataDir, "system"); 3830 File fname = new File(systemDir, "uiderrors.txt"); 3831 return fname; 3832 } 3833 3834 static void reportSettingsProblem(int priority, String msg) { 3835 try { 3836 File fname = getSettingsProblemFile(); 3837 FileOutputStream out = new FileOutputStream(fname, true); 3838 PrintWriter pw = new FastPrintWriter(out); 3839 SimpleDateFormat formatter = new SimpleDateFormat(); 3840 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3841 pw.println(dateString + ": " + msg); 3842 pw.close(); 3843 FileUtils.setPermissions( 3844 fname.toString(), 3845 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3846 -1, -1); 3847 } catch (java.io.IOException e) { 3848 } 3849 Slog.println(priority, TAG, msg); 3850 } 3851 3852 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3853 PackageParser.Package pkg, File srcFile, int parseFlags) { 3854 if (GET_CERTIFICATES) { 3855 if (ps != null 3856 && ps.codePath.equals(srcFile) 3857 && ps.timeStamp == srcFile.lastModified()) { 3858 if (ps.signatures.mSignatures != null 3859 && ps.signatures.mSignatures.length != 0) { 3860 // Optimization: reuse the existing cached certificates 3861 // if the package appears to be unchanged. 3862 pkg.mSignatures = ps.signatures.mSignatures; 3863 return true; 3864 } 3865 3866 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3867 } else { 3868 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3869 } 3870 3871 if (!pp.collectCertificates(pkg, parseFlags)) { 3872 mLastScanError = pp.getParseError(); 3873 return false; 3874 } 3875 } 3876 return true; 3877 } 3878 3879 /* 3880 * Scan a package and return the newly parsed package. 3881 * Returns null in case of errors and the error code is stored in mLastScanError 3882 */ 3883 private PackageParser.Package scanPackageLI(File scanFile, 3884 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 3885 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 3886 String scanPath = scanFile.getPath(); 3887 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath); 3888 parseFlags |= mDefParseFlags; 3889 PackageParser pp = new PackageParser(scanPath); 3890 pp.setSeparateProcesses(mSeparateProcesses); 3891 pp.setOnlyCoreApps(mOnlyCore); 3892 final PackageParser.Package pkg = pp.parsePackage(scanFile, 3893 scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0); 3894 3895 if (pkg == null) { 3896 mLastScanError = pp.getParseError(); 3897 return null; 3898 } 3899 3900 PackageSetting ps = null; 3901 PackageSetting updatedPkg; 3902 // reader 3903 synchronized (mPackages) { 3904 // Look to see if we already know about this package. 3905 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 3906 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 3907 // This package has been renamed to its original name. Let's 3908 // use that. 3909 ps = mSettings.peekPackageLPr(oldName); 3910 } 3911 // If there was no original package, see one for the real package name. 3912 if (ps == null) { 3913 ps = mSettings.peekPackageLPr(pkg.packageName); 3914 } 3915 // Check to see if this package could be hiding/updating a system 3916 // package. Must look for it either under the original or real 3917 // package name depending on our state. 3918 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 3919 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 3920 } 3921 boolean updatedPkgBetter = false; 3922 // First check if this is a system package that may involve an update 3923 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3924 if (ps != null && !ps.codePath.equals(scanFile)) { 3925 // The path has changed from what was last scanned... check the 3926 // version of the new path against what we have stored to determine 3927 // what to do. 3928 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 3929 if (pkg.mVersionCode < ps.versionCode) { 3930 // The system package has been updated and the code path does not match 3931 // Ignore entry. Skip it. 3932 Log.i(TAG, "Package " + ps.name + " at " + scanFile 3933 + " ignored: updated version " + ps.versionCode 3934 + " better than this " + pkg.mVersionCode); 3935 if (!updatedPkg.codePath.equals(scanFile)) { 3936 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : " 3937 + ps.name + " changing from " + updatedPkg.codePathString 3938 + " to " + scanFile); 3939 updatedPkg.codePath = scanFile; 3940 updatedPkg.codePathString = scanFile.toString(); 3941 // This is the point at which we know that the system-disk APK 3942 // for this package has moved during a reboot (e.g. due to an OTA), 3943 // so we need to reevaluate it for privilege policy. 3944 if (locationIsPrivileged(scanFile)) { 3945 updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED; 3946 } 3947 } 3948 updatedPkg.pkg = pkg; 3949 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3950 return null; 3951 } else { 3952 // The current app on the system partition is better than 3953 // what we have updated to on the data partition; switch 3954 // back to the system partition version. 3955 // At this point, its safely assumed that package installation for 3956 // apps in system partition will go through. If not there won't be a working 3957 // version of the app 3958 // writer 3959 synchronized (mPackages) { 3960 // Just remove the loaded entries from package lists. 3961 mPackages.remove(ps.name); 3962 } 3963 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 3964 + "reverting from " + ps.codePathString 3965 + ": new version " + pkg.mVersionCode 3966 + " better than installed " + ps.versionCode); 3967 3968 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3969 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 3970 getAppInstructionSetFromSettings(ps)); 3971 synchronized (mInstallLock) { 3972 args.cleanUpResourcesLI(); 3973 } 3974 synchronized (mPackages) { 3975 mSettings.enableSystemPackageLPw(ps.name); 3976 } 3977 updatedPkgBetter = true; 3978 } 3979 } 3980 } 3981 3982 if (updatedPkg != null) { 3983 // An updated system app will not have the PARSE_IS_SYSTEM flag set 3984 // initially 3985 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 3986 3987 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 3988 // flag set initially 3989 if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) { 3990 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 3991 } 3992 } 3993 // Verify certificates against what was last scanned 3994 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 3995 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 3996 return null; 3997 } 3998 3999 /* 4000 * A new system app appeared, but we already had a non-system one of the 4001 * same name installed earlier. 4002 */ 4003 boolean shouldHideSystemApp = false; 4004 if (updatedPkg == null && ps != null 4005 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 4006 /* 4007 * Check to make sure the signatures match first. If they don't, 4008 * wipe the installed application and its data. 4009 */ 4010 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 4011 != PackageManager.SIGNATURE_MATCH) { 4012 if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!"); 4013 deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false); 4014 ps = null; 4015 } else { 4016 /* 4017 * If the newly-added system app is an older version than the 4018 * already installed version, hide it. It will be scanned later 4019 * and re-added like an update. 4020 */ 4021 if (pkg.mVersionCode < ps.versionCode) { 4022 shouldHideSystemApp = true; 4023 } else { 4024 /* 4025 * The newly found system app is a newer version that the 4026 * one previously installed. Simply remove the 4027 * already-installed application and replace it with our own 4028 * while keeping the application data. 4029 */ 4030 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 4031 + ps.codePathString + ": new version " + pkg.mVersionCode 4032 + " better than installed " + ps.versionCode); 4033 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 4034 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString, 4035 getAppInstructionSetFromSettings(ps)); 4036 synchronized (mInstallLock) { 4037 args.cleanUpResourcesLI(); 4038 } 4039 } 4040 } 4041 } 4042 4043 // The apk is forward locked (not public) if its code and resources 4044 // are kept in different files. (except for app in either system or 4045 // vendor path). 4046 // TODO grab this value from PackageSettings 4047 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4048 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 4049 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 4050 } 4051 } 4052 4053 String codePath = null; 4054 String resPath = null; 4055 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 4056 if (ps != null && ps.resourcePathString != null) { 4057 resPath = ps.resourcePathString; 4058 } else { 4059 // Should not happen at all. Just log an error. 4060 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 4061 } 4062 } else { 4063 resPath = pkg.mScanPath; 4064 } 4065 4066 codePath = pkg.mScanPath; 4067 // Set application objects path explicitly. 4068 setApplicationInfoPaths(pkg, codePath, resPath); 4069 // Note that we invoke the following method only if we are about to unpack an application 4070 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 4071 | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride); 4072 4073 /* 4074 * If the system app should be overridden by a previously installed 4075 * data, hide the system app now and let the /data/app scan pick it up 4076 * again. 4077 */ 4078 if (shouldHideSystemApp) { 4079 synchronized (mPackages) { 4080 /* 4081 * We have to grant systems permissions before we hide, because 4082 * grantPermissions will assume the package update is trying to 4083 * expand its permissions. 4084 */ 4085 grantPermissionsLPw(pkg, true); 4086 mSettings.disableSystemPackageLPw(pkg.packageName); 4087 } 4088 } 4089 4090 return scannedPkg; 4091 } 4092 4093 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 4094 String destResPath) { 4095 pkg.mPath = pkg.mScanPath = destCodePath; 4096 pkg.applicationInfo.sourceDir = destCodePath; 4097 pkg.applicationInfo.publicSourceDir = destResPath; 4098 } 4099 4100 private static String fixProcessName(String defProcessName, 4101 String processName, int uid) { 4102 if (processName == null) { 4103 return defProcessName; 4104 } 4105 return processName; 4106 } 4107 4108 private boolean verifySignaturesLP(PackageSetting pkgSetting, 4109 PackageParser.Package pkg) { 4110 if (pkgSetting.signatures.mSignatures != null) { 4111 // Already existing package. Make sure signatures match 4112 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) != 4113 PackageManager.SIGNATURE_MATCH) { 4114 Slog.e(TAG, "Package " + pkg.packageName 4115 + " signatures do not match the previously installed version; ignoring!"); 4116 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 4117 return false; 4118 } 4119 } 4120 // Check for shared user signatures 4121 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 4122 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4123 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4124 Slog.e(TAG, "Package " + pkg.packageName 4125 + " has no signatures that match those in shared user " 4126 + pkgSetting.sharedUser.name + "; ignoring!"); 4127 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 4128 return false; 4129 } 4130 } 4131 return true; 4132 } 4133 4134 /** 4135 * Enforces that only the system UID or root's UID can call a method exposed 4136 * via Binder. 4137 * 4138 * @param message used as message if SecurityException is thrown 4139 * @throws SecurityException if the caller is not system or root 4140 */ 4141 private static final void enforceSystemOrRoot(String message) { 4142 final int uid = Binder.getCallingUid(); 4143 if (uid != Process.SYSTEM_UID && uid != 0) { 4144 throw new SecurityException(message); 4145 } 4146 } 4147 4148 @Override 4149 public void performBootDexOpt() { 4150 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4151 4152 final HashSet<PackageParser.Package> pkgs; 4153 synchronized (mPackages) { 4154 pkgs = mDeferredDexOpt; 4155 mDeferredDexOpt = null; 4156 } 4157 4158 if (pkgs != null) { 4159 // Filter out packages that aren't recently used. 4160 // 4161 // The exception is first boot of a non-eng device, which 4162 // should do a full dexopt. 4163 boolean eng = "eng".equals(SystemProperties.get("ro.build.type")); 4164 if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) { 4165 // TODO: add a property to control this? 4166 long dexOptLRUThresholdInMinutes; 4167 if (eng) { 4168 dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds. 4169 } else { 4170 dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users. 4171 } 4172 long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000; 4173 4174 int total = pkgs.size(); 4175 int skipped = 0; 4176 long now = System.currentTimeMillis(); 4177 for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) { 4178 PackageParser.Package pkg = i.next(); 4179 long then = pkg.mLastPackageUsageTimeInMills; 4180 if (then + dexOptLRUThresholdInMills < now) { 4181 if (DEBUG_DEXOPT) { 4182 Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " + 4183 ((then == 0) ? "never" : new Date(then))); 4184 } 4185 i.remove(); 4186 skipped++; 4187 } 4188 } 4189 if (DEBUG_DEXOPT) { 4190 Log.i(TAG, "Skipped optimizing " + skipped + " of " + total); 4191 } 4192 } 4193 4194 int i = 0; 4195 for (PackageParser.Package pkg : pkgs) { 4196 i++; 4197 if (DEBUG_DEXOPT) { 4198 Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size() 4199 + ": " + pkg.packageName); 4200 } 4201 if (!isFirstBoot()) { 4202 try { 4203 ActivityManagerNative.getDefault().showBootMessage( 4204 mContext.getResources().getString( 4205 R.string.android_upgrading_apk, 4206 i, pkgs.size()), true); 4207 } catch (RemoteException e) { 4208 } 4209 } 4210 PackageParser.Package p = pkg; 4211 synchronized (mInstallLock) { 4212 if (p.mDexOptNeeded) { 4213 performDexOptLI(p, false /* force dex */, false /* defer */, 4214 true /* include dependencies */); 4215 } 4216 } 4217 } 4218 } 4219 } 4220 4221 @Override 4222 public boolean performDexOpt(String packageName) { 4223 enforceSystemOrRoot("Only the system can request dexopt be performed"); 4224 return performDexOpt(packageName, true); 4225 } 4226 4227 public boolean performDexOpt(String packageName, boolean updateUsage) { 4228 4229 PackageParser.Package p; 4230 synchronized (mPackages) { 4231 p = mPackages.get(packageName); 4232 if (p == null) { 4233 return false; 4234 } 4235 if (updateUsage) { 4236 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 4237 } 4238 mPackageUsage.write(false); 4239 if (!p.mDexOptNeeded) { 4240 return false; 4241 } 4242 } 4243 4244 synchronized (mInstallLock) { 4245 return performDexOptLI(p, false /* force dex */, false /* defer */, 4246 true /* include dependencies */) == DEX_OPT_PERFORMED; 4247 } 4248 } 4249 4250 public HashSet<String> getPackagesThatNeedDexOpt() { 4251 HashSet<String> pkgs = null; 4252 synchronized (mPackages) { 4253 for (PackageParser.Package p : mPackages.values()) { 4254 if (DEBUG_DEXOPT) { 4255 Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded); 4256 } 4257 if (!p.mDexOptNeeded) { 4258 continue; 4259 } 4260 if (pkgs == null) { 4261 pkgs = new HashSet<String>(); 4262 } 4263 pkgs.add(p.packageName); 4264 } 4265 } 4266 return pkgs; 4267 } 4268 4269 public void shutdown() { 4270 mPackageUsage.write(true); 4271 } 4272 4273 private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet, 4274 boolean forceDex, boolean defer, HashSet<String> done) { 4275 for (int i=0; i<libs.size(); i++) { 4276 PackageParser.Package libPkg; 4277 String libName; 4278 synchronized (mPackages) { 4279 libName = libs.get(i); 4280 SharedLibraryEntry lib = mSharedLibraries.get(libName); 4281 if (lib != null && lib.apk != null) { 4282 libPkg = mPackages.get(lib.apk); 4283 } else { 4284 libPkg = null; 4285 } 4286 } 4287 if (libPkg != null && !done.contains(libName)) { 4288 performDexOptLI(libPkg, instructionSet, forceDex, defer, done); 4289 } 4290 } 4291 } 4292 4293 static final int DEX_OPT_SKIPPED = 0; 4294 static final int DEX_OPT_PERFORMED = 1; 4295 static final int DEX_OPT_DEFERRED = 2; 4296 static final int DEX_OPT_FAILED = -1; 4297 4298 private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride, 4299 boolean forceDex, boolean defer, HashSet<String> done) { 4300 final String instructionSet = instructionSetOverride != null ? 4301 instructionSetOverride : getAppInstructionSet(pkg.applicationInfo); 4302 4303 if (done != null) { 4304 done.add(pkg.packageName); 4305 if (pkg.usesLibraries != null) { 4306 performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done); 4307 } 4308 if (pkg.usesOptionalLibraries != null) { 4309 performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done); 4310 } 4311 } 4312 4313 boolean performed = false; 4314 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 4315 String path = pkg.mScanPath; 4316 try { 4317 boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path, 4318 pkg.packageName, 4319 instructionSet, 4320 defer); 4321 // There are three basic cases here: 4322 // 1.) we need to dexopt, either because we are forced or it is needed 4323 // 2.) we are defering a needed dexopt 4324 // 3.) we are skipping an unneeded dexopt 4325 if (forceDex || (!defer && isDexOptNeededInternal)) { 4326 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 4327 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 4328 int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg), 4329 pkg.packageName, instructionSet); 4330 // Note that we ran dexopt, since rerunning will 4331 // probably just result in an error again. 4332 pkg.mDexOptNeeded = false; 4333 if (ret < 0) { 4334 return DEX_OPT_FAILED; 4335 } 4336 return DEX_OPT_PERFORMED; 4337 } 4338 if (defer && isDexOptNeededInternal) { 4339 if (mDeferredDexOpt == null) { 4340 mDeferredDexOpt = new HashSet<PackageParser.Package>(); 4341 } 4342 mDeferredDexOpt.add(pkg); 4343 return DEX_OPT_DEFERRED; 4344 } 4345 pkg.mDexOptNeeded = false; 4346 return DEX_OPT_SKIPPED; 4347 } catch (FileNotFoundException e) { 4348 Slog.w(TAG, "Apk not found for dexopt: " + path); 4349 return DEX_OPT_FAILED; 4350 } catch (IOException e) { 4351 Slog.w(TAG, "IOException reading apk: " + path, e); 4352 return DEX_OPT_FAILED; 4353 } catch (StaleDexCacheError e) { 4354 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 4355 return DEX_OPT_FAILED; 4356 } catch (Exception e) { 4357 Slog.w(TAG, "Exception when doing dexopt : ", e); 4358 return DEX_OPT_FAILED; 4359 } 4360 } 4361 return DEX_OPT_SKIPPED; 4362 } 4363 4364 private String getAppInstructionSet(ApplicationInfo info) { 4365 String instructionSet = getPreferredInstructionSet(); 4366 4367 if (info.cpuAbi != null) { 4368 instructionSet = VMRuntime.getInstructionSet(info.cpuAbi); 4369 } 4370 4371 return instructionSet; 4372 } 4373 4374 private String getAppInstructionSetFromSettings(PackageSetting ps) { 4375 String instructionSet = getPreferredInstructionSet(); 4376 4377 if (ps.cpuAbiString != null) { 4378 instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 4379 } 4380 4381 return instructionSet; 4382 } 4383 4384 private static String getPreferredInstructionSet() { 4385 if (sPreferredInstructionSet == null) { 4386 sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]); 4387 } 4388 4389 return sPreferredInstructionSet; 4390 } 4391 4392 private static List<String> getAllInstructionSets() { 4393 final String[] allAbis = Build.SUPPORTED_ABIS; 4394 final List<String> allInstructionSets = new ArrayList<String>(allAbis.length); 4395 4396 for (String abi : allAbis) { 4397 final String instructionSet = VMRuntime.getInstructionSet(abi); 4398 if (!allInstructionSets.contains(instructionSet)) { 4399 allInstructionSets.add(instructionSet); 4400 } 4401 } 4402 4403 return allInstructionSets; 4404 } 4405 4406 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer, 4407 boolean inclDependencies) { 4408 HashSet<String> done; 4409 if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) { 4410 done = new HashSet<String>(); 4411 done.add(pkg.packageName); 4412 } else { 4413 done = null; 4414 } 4415 return performDexOptLI(pkg, null /* instruction set override */, forceDex, defer, done); 4416 } 4417 4418 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 4419 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 4420 Slog.w(TAG, "Unable to update from " + oldPkg.name 4421 + " to " + newPkg.packageName 4422 + ": old package not in system partition"); 4423 return false; 4424 } else if (mPackages.get(oldPkg.name) != null) { 4425 Slog.w(TAG, "Unable to update from " + oldPkg.name 4426 + " to " + newPkg.packageName 4427 + ": old package still exists"); 4428 return false; 4429 } 4430 return true; 4431 } 4432 4433 File getDataPathForUser(int userId) { 4434 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 4435 } 4436 4437 private File getDataPathForPackage(String packageName, int userId) { 4438 /* 4439 * Until we fully support multiple users, return the directory we 4440 * previously would have. The PackageManagerTests will need to be 4441 * revised when this is changed back.. 4442 */ 4443 if (userId == 0) { 4444 return new File(mAppDataDir, packageName); 4445 } else { 4446 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 4447 + File.separator + packageName); 4448 } 4449 } 4450 4451 private int createDataDirsLI(String packageName, int uid, String seinfo) { 4452 int[] users = sUserManager.getUserIds(); 4453 int res = mInstaller.install(packageName, uid, uid, seinfo); 4454 if (res < 0) { 4455 return res; 4456 } 4457 for (int user : users) { 4458 if (user != 0) { 4459 res = mInstaller.createUserData(packageName, 4460 UserHandle.getUid(user, uid), user, seinfo); 4461 if (res < 0) { 4462 return res; 4463 } 4464 } 4465 } 4466 return res; 4467 } 4468 4469 private int removeDataDirsLI(String packageName) { 4470 int[] users = sUserManager.getUserIds(); 4471 int res = 0; 4472 for (int user : users) { 4473 int resInner = mInstaller.remove(packageName, user); 4474 if (resInner < 0) { 4475 res = resInner; 4476 } 4477 } 4478 4479 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 4480 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 4481 if (!nativeLibraryFile.delete()) { 4482 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 4483 } 4484 4485 return res; 4486 } 4487 4488 private int addSharedLibraryLPw(final SharedLibraryEntry file, int num, 4489 PackageParser.Package changingLib) { 4490 if (file.path != null) { 4491 mTmpSharedLibraries[num] = file.path; 4492 return num+1; 4493 } 4494 PackageParser.Package p = mPackages.get(file.apk); 4495 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 4496 // If we are doing this while in the middle of updating a library apk, 4497 // then we need to make sure to use that new apk for determining the 4498 // dependencies here. (We haven't yet finished committing the new apk 4499 // to the package manager state.) 4500 if (p == null || p.packageName.equals(changingLib.packageName)) { 4501 p = changingLib; 4502 } 4503 } 4504 if (p != null) { 4505 String path = p.mPath; 4506 for (int i=0; i<num; i++) { 4507 if (mTmpSharedLibraries[i].equals(path)) { 4508 return num; 4509 } 4510 } 4511 mTmpSharedLibraries[num] = p.mPath; 4512 return num+1; 4513 } 4514 return num; 4515 } 4516 4517 private boolean updateSharedLibrariesLPw(PackageParser.Package pkg, 4518 PackageParser.Package changingLib) { 4519 // We might be upgrading from a version of the platform that did not 4520 // provide per-package native library directories for system apps. 4521 // Fix that up here. 4522 if (isSystemApp(pkg)) { 4523 PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName); 4524 setInternalAppNativeLibraryPath(pkg, ps); 4525 } 4526 4527 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 4528 if (mTmpSharedLibraries == null || 4529 mTmpSharedLibraries.length < mSharedLibraries.size()) { 4530 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 4531 } 4532 int num = 0; 4533 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 4534 for (int i=0; i<N; i++) { 4535 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 4536 if (file == null) { 4537 Slog.e(TAG, "Package " + pkg.packageName 4538 + " requires unavailable shared library " 4539 + pkg.usesLibraries.get(i) + "; failing!"); 4540 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 4541 return false; 4542 } 4543 num = addSharedLibraryLPw(file, num, changingLib); 4544 } 4545 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 4546 for (int i=0; i<N; i++) { 4547 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 4548 if (file == null) { 4549 Slog.w(TAG, "Package " + pkg.packageName 4550 + " desires unavailable shared library " 4551 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 4552 } else { 4553 num = addSharedLibraryLPw(file, num, changingLib); 4554 } 4555 } 4556 if (num > 0) { 4557 pkg.usesLibraryFiles = new String[num]; 4558 System.arraycopy(mTmpSharedLibraries, 0, 4559 pkg.usesLibraryFiles, 0, num); 4560 } else { 4561 pkg.usesLibraryFiles = null; 4562 } 4563 } 4564 return true; 4565 } 4566 4567 private static boolean hasString(List<String> list, List<String> which) { 4568 if (list == null) { 4569 return false; 4570 } 4571 for (int i=list.size()-1; i>=0; i--) { 4572 for (int j=which.size()-1; j>=0; j--) { 4573 if (which.get(j).equals(list.get(i))) { 4574 return true; 4575 } 4576 } 4577 } 4578 return false; 4579 } 4580 4581 private void updateAllSharedLibrariesLPw() { 4582 for (PackageParser.Package pkg : mPackages.values()) { 4583 updateSharedLibrariesLPw(pkg, null); 4584 } 4585 } 4586 4587 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 4588 PackageParser.Package changingPkg) { 4589 ArrayList<PackageParser.Package> res = null; 4590 for (PackageParser.Package pkg : mPackages.values()) { 4591 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 4592 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 4593 if (res == null) { 4594 res = new ArrayList<PackageParser.Package>(); 4595 } 4596 res.add(pkg); 4597 updateSharedLibrariesLPw(pkg, changingPkg); 4598 } 4599 } 4600 return res; 4601 } 4602 4603 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 4604 int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) { 4605 File scanFile = new File(pkg.mScanPath); 4606 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 4607 pkg.applicationInfo.publicSourceDir == null) { 4608 // Bail out. The resource and code paths haven't been set. 4609 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 4610 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 4611 return null; 4612 } 4613 4614 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 4615 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 4616 } 4617 4618 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 4619 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED; 4620 } 4621 4622 if (mCustomResolverComponentName != null && 4623 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 4624 setUpCustomResolverActivity(pkg); 4625 } 4626 4627 if (pkg.packageName.equals("android")) { 4628 synchronized (mPackages) { 4629 if (mAndroidApplication != null) { 4630 Slog.w(TAG, "*************************************************"); 4631 Slog.w(TAG, "Core android package being redefined. Skipping."); 4632 Slog.w(TAG, " file=" + scanFile); 4633 Slog.w(TAG, "*************************************************"); 4634 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4635 return null; 4636 } 4637 4638 // Set up information for our fall-back user intent resolution activity. 4639 mPlatformPackage = pkg; 4640 pkg.mVersionCode = mSdkVersion; 4641 mAndroidApplication = pkg.applicationInfo; 4642 4643 if (!mResolverReplaced) { 4644 mResolveActivity.applicationInfo = mAndroidApplication; 4645 mResolveActivity.name = ResolverActivity.class.getName(); 4646 mResolveActivity.packageName = mAndroidApplication.packageName; 4647 mResolveActivity.processName = "system:ui"; 4648 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 4649 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 4650 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 4651 mResolveActivity.exported = true; 4652 mResolveActivity.enabled = true; 4653 mResolveInfo.activityInfo = mResolveActivity; 4654 mResolveInfo.priority = 0; 4655 mResolveInfo.preferredOrder = 0; 4656 mResolveInfo.match = 0; 4657 mResolveComponentName = new ComponentName( 4658 mAndroidApplication.packageName, mResolveActivity.name); 4659 } 4660 } 4661 } 4662 4663 if (DEBUG_PACKAGE_SCANNING) { 4664 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4665 Log.d(TAG, "Scanning package " + pkg.packageName); 4666 } 4667 4668 if (mPackages.containsKey(pkg.packageName) 4669 || mSharedLibraries.containsKey(pkg.packageName)) { 4670 Slog.w(TAG, "Application package " + pkg.packageName 4671 + " already installed. Skipping duplicate."); 4672 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 4673 return null; 4674 } 4675 4676 // Initialize package source and resource directories 4677 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 4678 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 4679 4680 SharedUserSetting suid = null; 4681 PackageSetting pkgSetting = null; 4682 4683 if (!isSystemApp(pkg)) { 4684 // Only system apps can use these features. 4685 pkg.mOriginalPackages = null; 4686 pkg.mRealPackage = null; 4687 pkg.mAdoptPermissions = null; 4688 } 4689 4690 // writer 4691 synchronized (mPackages) { 4692 if (pkg.mSharedUserId != null) { 4693 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true); 4694 if (suid == null) { 4695 Slog.w(TAG, "Creating application package " + pkg.packageName 4696 + " for shared user failed"); 4697 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4698 return null; 4699 } 4700 if (DEBUG_PACKAGE_SCANNING) { 4701 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4702 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 4703 + "): packages=" + suid.packages); 4704 } 4705 } 4706 4707 // Check if we are renaming from an original package name. 4708 PackageSetting origPackage = null; 4709 String realName = null; 4710 if (pkg.mOriginalPackages != null) { 4711 // This package may need to be renamed to a previously 4712 // installed name. Let's check on that... 4713 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 4714 if (pkg.mOriginalPackages.contains(renamed)) { 4715 // This package had originally been installed as the 4716 // original name, and we have already taken care of 4717 // transitioning to the new one. Just update the new 4718 // one to continue using the old name. 4719 realName = pkg.mRealPackage; 4720 if (!pkg.packageName.equals(renamed)) { 4721 // Callers into this function may have already taken 4722 // care of renaming the package; only do it here if 4723 // it is not already done. 4724 pkg.setPackageName(renamed); 4725 } 4726 4727 } else { 4728 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 4729 if ((origPackage = mSettings.peekPackageLPr( 4730 pkg.mOriginalPackages.get(i))) != null) { 4731 // We do have the package already installed under its 4732 // original name... should we use it? 4733 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 4734 // New package is not compatible with original. 4735 origPackage = null; 4736 continue; 4737 } else if (origPackage.sharedUser != null) { 4738 // Make sure uid is compatible between packages. 4739 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 4740 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 4741 + " to " + pkg.packageName + ": old uid " 4742 + origPackage.sharedUser.name 4743 + " differs from " + pkg.mSharedUserId); 4744 origPackage = null; 4745 continue; 4746 } 4747 } else { 4748 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 4749 + pkg.packageName + " to old name " + origPackage.name); 4750 } 4751 break; 4752 } 4753 } 4754 } 4755 } 4756 4757 if (mTransferedPackages.contains(pkg.packageName)) { 4758 Slog.w(TAG, "Package " + pkg.packageName 4759 + " was transferred to another, but its .apk remains"); 4760 } 4761 4762 // Just create the setting, don't add it yet. For already existing packages 4763 // the PkgSetting exists already and doesn't have to be created. 4764 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 4765 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 4766 pkg.applicationInfo.cpuAbi, 4767 pkg.applicationInfo.flags, user, false); 4768 if (pkgSetting == null) { 4769 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 4770 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4771 return null; 4772 } 4773 4774 if (pkgSetting.origPackage != null) { 4775 // If we are first transitioning from an original package, 4776 // fix up the new package's name now. We need to do this after 4777 // looking up the package under its new name, so getPackageLP 4778 // can take care of fiddling things correctly. 4779 pkg.setPackageName(origPackage.name); 4780 4781 // File a report about this. 4782 String msg = "New package " + pkgSetting.realName 4783 + " renamed to replace old package " + pkgSetting.name; 4784 reportSettingsProblem(Log.WARN, msg); 4785 4786 // Make a note of it. 4787 mTransferedPackages.add(origPackage.name); 4788 4789 // No longer need to retain this. 4790 pkgSetting.origPackage = null; 4791 } 4792 4793 if (realName != null) { 4794 // Make a note of it. 4795 mTransferedPackages.add(pkg.packageName); 4796 } 4797 4798 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 4799 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 4800 } 4801 4802 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4803 // Check all shared libraries and map to their actual file path. 4804 // We only do this here for apps not on a system dir, because those 4805 // are the only ones that can fail an install due to this. We 4806 // will take care of the system apps by updating all of their 4807 // library paths after the scan is done. 4808 if (!updateSharedLibrariesLPw(pkg, null)) { 4809 return null; 4810 } 4811 } 4812 4813 if (mFoundPolicyFile) { 4814 SELinuxMMAC.assignSeinfoValue(pkg); 4815 } 4816 4817 pkg.applicationInfo.uid = pkgSetting.appId; 4818 pkg.mExtras = pkgSetting; 4819 4820 if (!verifySignaturesLP(pkgSetting, pkg)) { 4821 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 4822 return null; 4823 } 4824 // The signature has changed, but this package is in the system 4825 // image... let's recover! 4826 pkgSetting.signatures.mSignatures = pkg.mSignatures; 4827 // However... if this package is part of a shared user, but it 4828 // doesn't match the signature of the shared user, let's fail. 4829 // What this means is that you can't change the signatures 4830 // associated with an overall shared user, which doesn't seem all 4831 // that unreasonable. 4832 if (pkgSetting.sharedUser != null) { 4833 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 4834 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 4835 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 4836 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 4837 return null; 4838 } 4839 } 4840 // File a report about this. 4841 String msg = "System package " + pkg.packageName 4842 + " signature changed; retaining data."; 4843 reportSettingsProblem(Log.WARN, msg); 4844 } 4845 4846 // Verify that this new package doesn't have any content providers 4847 // that conflict with existing packages. Only do this if the 4848 // package isn't already installed, since we don't want to break 4849 // things that are installed. 4850 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 4851 final int N = pkg.providers.size(); 4852 int i; 4853 for (i=0; i<N; i++) { 4854 PackageParser.Provider p = pkg.providers.get(i); 4855 if (p.info.authority != null) { 4856 String names[] = p.info.authority.split(";"); 4857 for (int j = 0; j < names.length; j++) { 4858 if (mProvidersByAuthority.containsKey(names[j])) { 4859 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 4860 Slog.w(TAG, "Can't install because provider name " + names[j] + 4861 " (in package " + pkg.applicationInfo.packageName + 4862 ") is already used by " 4863 + ((other != null && other.getComponentName() != null) 4864 ? other.getComponentName().getPackageName() : "?")); 4865 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 4866 return null; 4867 } 4868 } 4869 } 4870 } 4871 } 4872 4873 if (pkg.mAdoptPermissions != null) { 4874 // This package wants to adopt ownership of permissions from 4875 // another package. 4876 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 4877 final String origName = pkg.mAdoptPermissions.get(i); 4878 final PackageSetting orig = mSettings.peekPackageLPr(origName); 4879 if (orig != null) { 4880 if (verifyPackageUpdateLPr(orig, pkg)) { 4881 Slog.i(TAG, "Adopting permissions from " + origName + " to " 4882 + pkg.packageName); 4883 mSettings.transferPermissionsLPw(origName, pkg.packageName); 4884 } 4885 } 4886 } 4887 } 4888 } 4889 4890 final String pkgName = pkg.packageName; 4891 4892 final long scanFileTime = scanFile.lastModified(); 4893 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 4894 pkg.applicationInfo.processName = fixProcessName( 4895 pkg.applicationInfo.packageName, 4896 pkg.applicationInfo.processName, 4897 pkg.applicationInfo.uid); 4898 4899 File dataPath; 4900 if (mPlatformPackage == pkg) { 4901 // The system package is special. 4902 dataPath = new File (Environment.getDataDirectory(), "system"); 4903 pkg.applicationInfo.dataDir = dataPath.getPath(); 4904 } else { 4905 // This is a normal package, need to make its data directory. 4906 dataPath = getDataPathForPackage(pkg.packageName, 0); 4907 4908 boolean uidError = false; 4909 4910 if (dataPath.exists()) { 4911 int currentUid = 0; 4912 try { 4913 StructStat stat = Os.stat(dataPath.getPath()); 4914 currentUid = stat.st_uid; 4915 } catch (ErrnoException e) { 4916 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 4917 } 4918 4919 // If we have mismatched owners for the data path, we have a problem. 4920 if (currentUid != pkg.applicationInfo.uid) { 4921 boolean recovered = false; 4922 if (currentUid == 0) { 4923 // The directory somehow became owned by root. Wow. 4924 // This is probably because the system was stopped while 4925 // installd was in the middle of messing with its libs 4926 // directory. Ask installd to fix that. 4927 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 4928 pkg.applicationInfo.uid); 4929 if (ret >= 0) { 4930 recovered = true; 4931 String msg = "Package " + pkg.packageName 4932 + " unexpectedly changed to uid 0; recovered to " + 4933 + pkg.applicationInfo.uid; 4934 reportSettingsProblem(Log.WARN, msg); 4935 } 4936 } 4937 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4938 || (scanMode&SCAN_BOOTING) != 0)) { 4939 // If this is a system app, we can at least delete its 4940 // current data so the application will still work. 4941 int ret = removeDataDirsLI(pkgName); 4942 if (ret >= 0) { 4943 // TODO: Kill the processes first 4944 // Old data gone! 4945 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4946 ? "System package " : "Third party package "; 4947 String msg = prefix + pkg.packageName 4948 + " has changed from uid: " 4949 + currentUid + " to " 4950 + pkg.applicationInfo.uid + "; old data erased"; 4951 reportSettingsProblem(Log.WARN, msg); 4952 recovered = true; 4953 4954 // And now re-install the app. 4955 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 4956 pkg.applicationInfo.seinfo); 4957 if (ret == -1) { 4958 // Ack should not happen! 4959 msg = prefix + pkg.packageName 4960 + " could not have data directory re-created after delete."; 4961 reportSettingsProblem(Log.WARN, msg); 4962 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4963 return null; 4964 } 4965 } 4966 if (!recovered) { 4967 mHasSystemUidErrors = true; 4968 } 4969 } else if (!recovered) { 4970 // If we allow this install to proceed, we will be broken. 4971 // Abort, abort! 4972 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 4973 return null; 4974 } 4975 if (!recovered) { 4976 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 4977 + pkg.applicationInfo.uid + "/fs_" 4978 + currentUid; 4979 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 4980 String msg = "Package " + pkg.packageName 4981 + " has mismatched uid: " 4982 + currentUid + " on disk, " 4983 + pkg.applicationInfo.uid + " in settings"; 4984 // writer 4985 synchronized (mPackages) { 4986 mSettings.mReadMessages.append(msg); 4987 mSettings.mReadMessages.append('\n'); 4988 uidError = true; 4989 if (!pkgSetting.uidError) { 4990 reportSettingsProblem(Log.ERROR, msg); 4991 } 4992 } 4993 } 4994 } 4995 pkg.applicationInfo.dataDir = dataPath.getPath(); 4996 if (mShouldRestoreconData) { 4997 Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued."); 4998 mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo, 4999 pkg.applicationInfo.uid); 5000 } 5001 } else { 5002 if (DEBUG_PACKAGE_SCANNING) { 5003 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5004 Log.v(TAG, "Want this data dir: " + dataPath); 5005 } 5006 //invoke installer to do the actual installation 5007 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid, 5008 pkg.applicationInfo.seinfo); 5009 if (ret < 0) { 5010 // Error from installer 5011 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 5012 return null; 5013 } 5014 5015 if (dataPath.exists()) { 5016 pkg.applicationInfo.dataDir = dataPath.getPath(); 5017 } else { 5018 Slog.w(TAG, "Unable to create data directory: " + dataPath); 5019 pkg.applicationInfo.dataDir = null; 5020 } 5021 } 5022 5023 /* 5024 * Set the data dir to the default "/data/data/<package name>/lib" 5025 * if we got here without anyone telling us different (e.g., apps 5026 * stored on SD card have their native libraries stored in the ASEC 5027 * container with the APK). 5028 * 5029 * This happens during an upgrade from a package settings file that 5030 * doesn't have a native library path attribute at all. 5031 */ 5032 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 5033 if (pkgSetting.nativeLibraryPathString == null) { 5034 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5035 } else { 5036 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 5037 } 5038 } 5039 pkgSetting.uidError = uidError; 5040 } 5041 5042 String path = scanFile.getPath(); 5043 /* Note: We don't want to unpack the native binaries for 5044 * system applications, unless they have been updated 5045 * (the binaries are already under /system/lib). 5046 * Also, don't unpack libs for apps on the external card 5047 * since they should have their libraries in the ASEC 5048 * container already. 5049 * 5050 * In other words, we're going to unpack the binaries 5051 * only for non-system apps and system app upgrades. 5052 */ 5053 if (pkg.applicationInfo.nativeLibraryDir != null) { 5054 ApkHandle handle = null; 5055 try { 5056 handle = ApkHandle.create(scanFile.getPath()); 5057 // Enable gross and lame hacks for apps that are built with old 5058 // SDK tools. We must scan their APKs for renderscript bitcode and 5059 // not launch them if it's present. Don't bother checking on devices 5060 // that don't have 64 bit support. 5061 String[] abiList = Build.SUPPORTED_ABIS; 5062 boolean hasLegacyRenderscriptBitcode = false; 5063 if (abiOverride != null) { 5064 abiList = new String[] { abiOverride }; 5065 } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 5066 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 5067 abiList = Build.SUPPORTED_32_BIT_ABIS; 5068 hasLegacyRenderscriptBitcode = true; 5069 } 5070 5071 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5072 final String dataPathString = dataPath.getCanonicalPath(); 5073 5074 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 5075 /* 5076 * Upgrading from a previous version of the OS sometimes 5077 * leaves native libraries in the /data/data/<app>/lib 5078 * directory for system apps even when they shouldn't be. 5079 * Recent changes in the JNI library search path 5080 * necessitates we remove those to match previous behavior. 5081 */ 5082 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 5083 Log.i(TAG, "removed obsolete native libraries for system package " 5084 + path); 5085 } 5086 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5087 pkg.applicationInfo.cpuAbi = abiList[0]; 5088 pkgSetting.cpuAbiString = abiList[0]; 5089 } else { 5090 setInternalAppAbi(pkg, pkgSetting); 5091 } 5092 } else { 5093 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 5094 /* 5095 * Update native library dir if it starts with 5096 * /data/data 5097 */ 5098 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 5099 setInternalAppNativeLibraryPath(pkg, pkgSetting); 5100 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 5101 } 5102 5103 try { 5104 int copyRet = copyNativeLibrariesForInternalApp(handle, 5105 nativeLibraryDir, abiList); 5106 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5107 Slog.e(TAG, "Unable to copy native libraries"); 5108 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5109 return null; 5110 } 5111 5112 // We've successfully copied native libraries across, so we make a 5113 // note of what ABI we're using 5114 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 5115 pkg.applicationInfo.cpuAbi = abiList[copyRet]; 5116 } else if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5117 pkg.applicationInfo.cpuAbi = abiList[0]; 5118 } else { 5119 pkg.applicationInfo.cpuAbi = null; 5120 } 5121 } catch (IOException e) { 5122 Slog.e(TAG, "Unable to copy native libraries", e); 5123 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5124 return null; 5125 } 5126 } else { 5127 // We don't have to copy the shared libraries if we're in the ASEC container 5128 // but we still need to scan the file to figure out what ABI the app needs. 5129 // 5130 // TODO: This duplicates work done in the default container service. It's possible 5131 // to clean this up but we'll need to change the interface between this service 5132 // and IMediaContainerService (but doing so will spread this logic out, rather 5133 // than centralizing it). 5134 final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5135 if (abi >= 0) { 5136 pkg.applicationInfo.cpuAbi = abiList[abi]; 5137 } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) { 5138 // Note that (non upgraded) system apps will not have any native 5139 // libraries bundled in their APK, but we're guaranteed not to be 5140 // such an app at this point. 5141 if (abiOverride != null || hasLegacyRenderscriptBitcode) { 5142 pkg.applicationInfo.cpuAbi = abiList[0]; 5143 } else { 5144 pkg.applicationInfo.cpuAbi = null; 5145 } 5146 } else { 5147 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5148 return null; 5149 } 5150 } 5151 5152 if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path); 5153 final int[] userIds = sUserManager.getUserIds(); 5154 synchronized (mInstallLock) { 5155 for (int userId : userIds) { 5156 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 5157 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 5158 Slog.w(TAG, "Failed linking native library dir (user=" + userId 5159 + ")"); 5160 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 5161 return null; 5162 } 5163 } 5164 } 5165 } 5166 5167 pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi; 5168 } catch (IOException ioe) { 5169 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 5170 } finally { 5171 IoUtils.closeQuietly(handle); 5172 } 5173 } 5174 pkg.mScanPath = path; 5175 5176 if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 5177 // We don't do this here during boot because we can do it all 5178 // at once after scanning all existing packages. 5179 // 5180 // We also do this *before* we perform dexopt on this package, so that 5181 // we can avoid redundant dexopts, and also to make sure we've got the 5182 // code and package path correct. 5183 if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 5184 pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) { 5185 mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE; 5186 return null; 5187 } 5188 } 5189 5190 if ((scanMode&SCAN_NO_DEX) == 0) { 5191 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5192 == DEX_OPT_FAILED) { 5193 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5194 removeDataDirsLI(pkg.packageName); 5195 } 5196 5197 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5198 return null; 5199 } 5200 } 5201 5202 if (mFactoryTest && pkg.requestedPermissions.contains( 5203 android.Manifest.permission.FACTORY_TEST)) { 5204 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 5205 } 5206 5207 ArrayList<PackageParser.Package> clientLibPkgs = null; 5208 5209 // writer 5210 synchronized (mPackages) { 5211 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 5212 // Only system apps can add new shared libraries. 5213 if (pkg.libraryNames != null) { 5214 for (int i=0; i<pkg.libraryNames.size(); i++) { 5215 String name = pkg.libraryNames.get(i); 5216 boolean allowed = false; 5217 if (isUpdatedSystemApp(pkg)) { 5218 // New library entries can only be added through the 5219 // system image. This is important to get rid of a lot 5220 // of nasty edge cases: for example if we allowed a non- 5221 // system update of the app to add a library, then uninstalling 5222 // the update would make the library go away, and assumptions 5223 // we made such as through app install filtering would now 5224 // have allowed apps on the device which aren't compatible 5225 // with it. Better to just have the restriction here, be 5226 // conservative, and create many fewer cases that can negatively 5227 // impact the user experience. 5228 final PackageSetting sysPs = mSettings 5229 .getDisabledSystemPkgLPr(pkg.packageName); 5230 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 5231 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 5232 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 5233 allowed = true; 5234 allowed = true; 5235 break; 5236 } 5237 } 5238 } 5239 } else { 5240 allowed = true; 5241 } 5242 if (allowed) { 5243 if (!mSharedLibraries.containsKey(name)) { 5244 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 5245 } else if (!name.equals(pkg.packageName)) { 5246 Slog.w(TAG, "Package " + pkg.packageName + " library " 5247 + name + " already exists; skipping"); 5248 } 5249 } else { 5250 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 5251 + name + " that is not declared on system image; skipping"); 5252 } 5253 } 5254 if ((scanMode&SCAN_BOOTING) == 0) { 5255 // If we are not booting, we need to update any applications 5256 // that are clients of our shared library. If we are booting, 5257 // this will all be done once the scan is complete. 5258 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 5259 } 5260 } 5261 } 5262 } 5263 5264 // We also need to dexopt any apps that are dependent on this library. Note that 5265 // if these fail, we should abort the install since installing the library will 5266 // result in some apps being broken. 5267 if (clientLibPkgs != null) { 5268 if ((scanMode&SCAN_NO_DEX) == 0) { 5269 for (int i=0; i<clientLibPkgs.size(); i++) { 5270 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5271 if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false) 5272 == DEX_OPT_FAILED) { 5273 if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 5274 removeDataDirsLI(pkg.packageName); 5275 } 5276 5277 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 5278 return null; 5279 } 5280 } 5281 } 5282 } 5283 5284 // Request the ActivityManager to kill the process(only for existing packages) 5285 // so that we do not end up in a confused state while the user is still using the older 5286 // version of the application while the new one gets installed. 5287 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 5288 // If the package lives in an asec, tell everyone that the container is going 5289 // away so they can clean up any references to its resources (which would prevent 5290 // vold from being able to unmount the asec) 5291 if (isForwardLocked(pkg) || isExternal(pkg)) { 5292 if (DEBUG_INSTALL) { 5293 Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE"); 5294 } 5295 final int[] uidArray = new int[] { pkg.applicationInfo.uid }; 5296 final ArrayList<String> pkgList = new ArrayList<String>(1); 5297 pkgList.add(pkg.applicationInfo.packageName); 5298 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 5299 } 5300 5301 // Post the request that it be killed now that the going-away broadcast is en route 5302 killApplication(pkg.applicationInfo.packageName, 5303 pkg.applicationInfo.uid, "update pkg"); 5304 } 5305 5306 // Also need to kill any apps that are dependent on the library. 5307 if (clientLibPkgs != null) { 5308 for (int i=0; i<clientLibPkgs.size(); i++) { 5309 PackageParser.Package clientPkg = clientLibPkgs.get(i); 5310 killApplication(clientPkg.applicationInfo.packageName, 5311 clientPkg.applicationInfo.uid, "update lib"); 5312 } 5313 } 5314 5315 // writer 5316 synchronized (mPackages) { 5317 // We don't expect installation to fail beyond this point, 5318 if ((scanMode&SCAN_MONITOR) != 0) { 5319 mAppDirs.put(pkg.mPath, pkg); 5320 } 5321 // Add the new setting to mSettings 5322 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 5323 // Add the new setting to mPackages 5324 mPackages.put(pkg.applicationInfo.packageName, pkg); 5325 // Make sure we don't accidentally delete its data. 5326 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 5327 while (iter.hasNext()) { 5328 PackageCleanItem item = iter.next(); 5329 if (pkgName.equals(item.packageName)) { 5330 iter.remove(); 5331 } 5332 } 5333 5334 // Take care of first install / last update times. 5335 if (currentTime != 0) { 5336 if (pkgSetting.firstInstallTime == 0) { 5337 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 5338 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 5339 pkgSetting.lastUpdateTime = currentTime; 5340 } 5341 } else if (pkgSetting.firstInstallTime == 0) { 5342 // We need *something*. Take time time stamp of the file. 5343 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 5344 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 5345 if (scanFileTime != pkgSetting.timeStamp) { 5346 // A package on the system image has changed; consider this 5347 // to be an update. 5348 pkgSetting.lastUpdateTime = scanFileTime; 5349 } 5350 } 5351 5352 // Add the package's KeySets to the global KeySetManager 5353 KeySetManager ksm = mSettings.mKeySetManager; 5354 try { 5355 ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys); 5356 if (pkg.mKeySetMapping != null) { 5357 for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) { 5358 if (entry.getValue() != null) { 5359 ksm.addDefinedKeySetToPackage(pkg.packageName, 5360 entry.getValue(), entry.getKey()); 5361 } 5362 } 5363 } 5364 } catch (NullPointerException e) { 5365 Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e); 5366 } catch (IllegalArgumentException e) { 5367 Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e); 5368 } 5369 5370 int N = pkg.providers.size(); 5371 StringBuilder r = null; 5372 int i; 5373 for (i=0; i<N; i++) { 5374 PackageParser.Provider p = pkg.providers.get(i); 5375 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 5376 p.info.processName, pkg.applicationInfo.uid); 5377 mProviders.addProvider(p); 5378 p.syncable = p.info.isSyncable; 5379 if (p.info.authority != null) { 5380 String names[] = p.info.authority.split(";"); 5381 p.info.authority = null; 5382 for (int j = 0; j < names.length; j++) { 5383 if (j == 1 && p.syncable) { 5384 // We only want the first authority for a provider to possibly be 5385 // syncable, so if we already added this provider using a different 5386 // authority clear the syncable flag. We copy the provider before 5387 // changing it because the mProviders object contains a reference 5388 // to a provider that we don't want to change. 5389 // Only do this for the second authority since the resulting provider 5390 // object can be the same for all future authorities for this provider. 5391 p = new PackageParser.Provider(p); 5392 p.syncable = false; 5393 } 5394 if (!mProvidersByAuthority.containsKey(names[j])) { 5395 mProvidersByAuthority.put(names[j], p); 5396 if (p.info.authority == null) { 5397 p.info.authority = names[j]; 5398 } else { 5399 p.info.authority = p.info.authority + ";" + names[j]; 5400 } 5401 if (DEBUG_PACKAGE_SCANNING) { 5402 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 5403 Log.d(TAG, "Registered content provider: " + names[j] 5404 + ", className = " + p.info.name + ", isSyncable = " 5405 + p.info.isSyncable); 5406 } 5407 } else { 5408 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 5409 Slog.w(TAG, "Skipping provider name " + names[j] + 5410 " (in package " + pkg.applicationInfo.packageName + 5411 "): name already used by " 5412 + ((other != null && other.getComponentName() != null) 5413 ? other.getComponentName().getPackageName() : "?")); 5414 } 5415 } 5416 } 5417 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5418 if (r == null) { 5419 r = new StringBuilder(256); 5420 } else { 5421 r.append(' '); 5422 } 5423 r.append(p.info.name); 5424 } 5425 } 5426 if (r != null) { 5427 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 5428 } 5429 5430 N = pkg.services.size(); 5431 r = null; 5432 for (i=0; i<N; i++) { 5433 PackageParser.Service s = pkg.services.get(i); 5434 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 5435 s.info.processName, pkg.applicationInfo.uid); 5436 mServices.addService(s); 5437 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5438 if (r == null) { 5439 r = new StringBuilder(256); 5440 } else { 5441 r.append(' '); 5442 } 5443 r.append(s.info.name); 5444 } 5445 } 5446 if (r != null) { 5447 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 5448 } 5449 5450 N = pkg.receivers.size(); 5451 r = null; 5452 for (i=0; i<N; i++) { 5453 PackageParser.Activity a = pkg.receivers.get(i); 5454 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5455 a.info.processName, pkg.applicationInfo.uid); 5456 mReceivers.addActivity(a, "receiver"); 5457 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5458 if (r == null) { 5459 r = new StringBuilder(256); 5460 } else { 5461 r.append(' '); 5462 } 5463 r.append(a.info.name); 5464 } 5465 } 5466 if (r != null) { 5467 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 5468 } 5469 5470 N = pkg.activities.size(); 5471 r = null; 5472 for (i=0; i<N; i++) { 5473 PackageParser.Activity a = pkg.activities.get(i); 5474 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 5475 a.info.processName, pkg.applicationInfo.uid); 5476 mActivities.addActivity(a, "activity"); 5477 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5478 if (r == null) { 5479 r = new StringBuilder(256); 5480 } else { 5481 r.append(' '); 5482 } 5483 r.append(a.info.name); 5484 } 5485 } 5486 if (r != null) { 5487 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 5488 } 5489 5490 N = pkg.permissionGroups.size(); 5491 r = null; 5492 for (i=0; i<N; i++) { 5493 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 5494 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 5495 if (cur == null) { 5496 mPermissionGroups.put(pg.info.name, pg); 5497 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5498 if (r == null) { 5499 r = new StringBuilder(256); 5500 } else { 5501 r.append(' '); 5502 } 5503 r.append(pg.info.name); 5504 } 5505 } else { 5506 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 5507 + pg.info.packageName + " ignored: original from " 5508 + cur.info.packageName); 5509 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5510 if (r == null) { 5511 r = new StringBuilder(256); 5512 } else { 5513 r.append(' '); 5514 } 5515 r.append("DUP:"); 5516 r.append(pg.info.name); 5517 } 5518 } 5519 } 5520 if (r != null) { 5521 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 5522 } 5523 5524 N = pkg.permissions.size(); 5525 r = null; 5526 for (i=0; i<N; i++) { 5527 PackageParser.Permission p = pkg.permissions.get(i); 5528 HashMap<String, BasePermission> permissionMap = 5529 p.tree ? mSettings.mPermissionTrees 5530 : mSettings.mPermissions; 5531 p.group = mPermissionGroups.get(p.info.group); 5532 if (p.info.group == null || p.group != null) { 5533 BasePermission bp = permissionMap.get(p.info.name); 5534 if (bp == null) { 5535 bp = new BasePermission(p.info.name, p.info.packageName, 5536 BasePermission.TYPE_NORMAL); 5537 permissionMap.put(p.info.name, bp); 5538 } 5539 if (bp.perm == null) { 5540 if (bp.sourcePackage != null 5541 && !bp.sourcePackage.equals(p.info.packageName)) { 5542 // If this is a permission that was formerly defined by a non-system 5543 // app, but is now defined by a system app (following an upgrade), 5544 // discard the previous declaration and consider the system's to be 5545 // canonical. 5546 if (isSystemApp(p.owner)) { 5547 Slog.i(TAG, "New decl " + p.owner + " of permission " 5548 + p.info.name + " is system"); 5549 bp.sourcePackage = null; 5550 } 5551 } 5552 if (bp.sourcePackage == null 5553 || bp.sourcePackage.equals(p.info.packageName)) { 5554 BasePermission tree = findPermissionTreeLP(p.info.name); 5555 if (tree == null 5556 || tree.sourcePackage.equals(p.info.packageName)) { 5557 bp.packageSetting = pkgSetting; 5558 bp.perm = p; 5559 bp.uid = pkg.applicationInfo.uid; 5560 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5561 if (r == null) { 5562 r = new StringBuilder(256); 5563 } else { 5564 r.append(' '); 5565 } 5566 r.append(p.info.name); 5567 } 5568 } else { 5569 Slog.w(TAG, "Permission " + p.info.name + " from package " 5570 + p.info.packageName + " ignored: base tree " 5571 + tree.name + " is from package " 5572 + tree.sourcePackage); 5573 } 5574 } else { 5575 Slog.w(TAG, "Permission " + p.info.name + " from package " 5576 + p.info.packageName + " ignored: original from " 5577 + bp.sourcePackage); 5578 } 5579 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5580 if (r == null) { 5581 r = new StringBuilder(256); 5582 } else { 5583 r.append(' '); 5584 } 5585 r.append("DUP:"); 5586 r.append(p.info.name); 5587 } 5588 if (bp.perm == p) { 5589 bp.protectionLevel = p.info.protectionLevel; 5590 } 5591 } else { 5592 Slog.w(TAG, "Permission " + p.info.name + " from package " 5593 + p.info.packageName + " ignored: no group " 5594 + p.group); 5595 } 5596 } 5597 if (r != null) { 5598 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 5599 } 5600 5601 N = pkg.instrumentation.size(); 5602 r = null; 5603 for (i=0; i<N; i++) { 5604 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 5605 a.info.packageName = pkg.applicationInfo.packageName; 5606 a.info.sourceDir = pkg.applicationInfo.sourceDir; 5607 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 5608 a.info.dataDir = pkg.applicationInfo.dataDir; 5609 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 5610 mInstrumentation.put(a.getComponentName(), a); 5611 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 5612 if (r == null) { 5613 r = new StringBuilder(256); 5614 } else { 5615 r.append(' '); 5616 } 5617 r.append(a.info.name); 5618 } 5619 } 5620 if (r != null) { 5621 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 5622 } 5623 5624 if (pkg.protectedBroadcasts != null) { 5625 N = pkg.protectedBroadcasts.size(); 5626 for (i=0; i<N; i++) { 5627 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 5628 } 5629 } 5630 5631 pkgSetting.setTimeStamp(scanFileTime); 5632 5633 // Create idmap files for pairs of (packages, overlay packages). 5634 // Note: "android", ie framework-res.apk, is handled by native layers. 5635 if (pkg.mOverlayTarget != null) { 5636 // This is an overlay package. 5637 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 5638 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 5639 mOverlays.put(pkg.mOverlayTarget, 5640 new HashMap<String, PackageParser.Package>()); 5641 } 5642 HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 5643 map.put(pkg.packageName, pkg); 5644 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 5645 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 5646 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 5647 return null; 5648 } 5649 } 5650 } else if (mOverlays.containsKey(pkg.packageName) && 5651 !pkg.packageName.equals("android")) { 5652 // This is a regular package, with one or more known overlay packages. 5653 createIdmapsForPackageLI(pkg); 5654 } 5655 } 5656 5657 return pkg; 5658 } 5659 5660 /** 5661 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 5662 * i.e, so that all packages can be run inside a single process if required. 5663 * 5664 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 5665 * this function will either try and make the ABI for all packages in {@code packagesForUser} 5666 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 5667 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 5668 * updating a package that belongs to a shared user. 5669 */ 5670 private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 5671 PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) { 5672 String requiredInstructionSet = null; 5673 if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) { 5674 requiredInstructionSet = VMRuntime.getInstructionSet( 5675 scannedPackage.applicationInfo.cpuAbi); 5676 } 5677 5678 PackageSetting requirer = null; 5679 for (PackageSetting ps : packagesForUser) { 5680 // If packagesForUser contains scannedPackage, we skip it. This will happen 5681 // when scannedPackage is an update of an existing package. Without this check, 5682 // we will never be able to change the ABI of any package belonging to a shared 5683 // user, even if it's compatible with other packages. 5684 if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) { 5685 if (ps.cpuAbiString == null) { 5686 continue; 5687 } 5688 5689 final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString); 5690 if (requiredInstructionSet != null) { 5691 if (!instructionSet.equals(requiredInstructionSet)) { 5692 // We have a mismatch between instruction sets (say arm vs arm64). 5693 // bail out. 5694 String errorMessage = "Instruction set mismatch, " 5695 + ((requirer == null) ? "[caller]" : requirer) 5696 + " requires " + requiredInstructionSet + " whereas " + ps 5697 + " requires " + instructionSet; 5698 Slog.e(TAG, errorMessage); 5699 5700 reportSettingsProblem(Log.WARN, errorMessage); 5701 // Give up, don't bother making any other changes to the package settings. 5702 return false; 5703 } 5704 } else { 5705 requiredInstructionSet = instructionSet; 5706 requirer = ps; 5707 } 5708 } 5709 } 5710 5711 if (requiredInstructionSet != null) { 5712 String adjustedAbi; 5713 if (requirer != null) { 5714 // requirer != null implies that either scannedPackage was null or that scannedPackage 5715 // did not require an ABI, in which case we have to adjust scannedPackage to match 5716 // the ABI of the set (which is the same as requirer's ABI) 5717 adjustedAbi = requirer.cpuAbiString; 5718 if (scannedPackage != null) { 5719 scannedPackage.applicationInfo.cpuAbi = adjustedAbi; 5720 } 5721 } else { 5722 // requirer == null implies that we're updating all ABIs in the set to 5723 // match scannedPackage. 5724 adjustedAbi = scannedPackage.applicationInfo.cpuAbi; 5725 } 5726 5727 for (PackageSetting ps : packagesForUser) { 5728 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 5729 if (ps.cpuAbiString != null) { 5730 continue; 5731 } 5732 5733 ps.cpuAbiString = adjustedAbi; 5734 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 5735 ps.pkg.applicationInfo.cpuAbi = adjustedAbi; 5736 Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi); 5737 5738 if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) { 5739 ps.cpuAbiString = null; 5740 ps.pkg.applicationInfo.cpuAbi = null; 5741 return false; 5742 } else { 5743 mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet()); 5744 } 5745 } 5746 } 5747 } 5748 } 5749 5750 return true; 5751 } 5752 5753 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 5754 synchronized (mPackages) { 5755 mResolverReplaced = true; 5756 // Set up information for custom user intent resolution activity. 5757 mResolveActivity.applicationInfo = pkg.applicationInfo; 5758 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 5759 mResolveActivity.packageName = pkg.applicationInfo.packageName; 5760 mResolveActivity.processName = null; 5761 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 5762 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 5763 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 5764 mResolveActivity.theme = 0; 5765 mResolveActivity.exported = true; 5766 mResolveActivity.enabled = true; 5767 mResolveInfo.activityInfo = mResolveActivity; 5768 mResolveInfo.priority = 0; 5769 mResolveInfo.preferredOrder = 0; 5770 mResolveInfo.match = 0; 5771 mResolveComponentName = mCustomResolverComponentName; 5772 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 5773 mResolveComponentName); 5774 } 5775 } 5776 5777 private String calculateApkRoot(final String codePathString) { 5778 final File codePath = new File(codePathString); 5779 final File codeRoot; 5780 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 5781 codeRoot = Environment.getRootDirectory(); 5782 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 5783 codeRoot = Environment.getOemDirectory(); 5784 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 5785 codeRoot = Environment.getVendorDirectory(); 5786 } else { 5787 // Unrecognized code path; take its top real segment as the apk root: 5788 // e.g. /something/app/blah.apk => /something 5789 try { 5790 File f = codePath.getCanonicalFile(); 5791 File parent = f.getParentFile(); // non-null because codePath is a file 5792 File tmp; 5793 while ((tmp = parent.getParentFile()) != null) { 5794 f = parent; 5795 parent = tmp; 5796 } 5797 codeRoot = f; 5798 Slog.w(TAG, "Unrecognized code path " 5799 + codePath + " - using " + codeRoot); 5800 } catch (IOException e) { 5801 // Can't canonicalize the lib path -- shenanigans? 5802 Slog.w(TAG, "Can't canonicalize code path " + codePath); 5803 return Environment.getRootDirectory().getPath(); 5804 } 5805 } 5806 return codeRoot.getPath(); 5807 } 5808 5809 // This is the initial scan-time determination of how to handle a given 5810 // package for purposes of native library location. 5811 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 5812 PackageSetting pkgSetting) { 5813 // "bundled" here means system-installed with no overriding update 5814 final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg); 5815 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5816 final File libDir; 5817 if (bundledApk) { 5818 // If "/system/lib64/apkname" exists, assume that is the per-package 5819 // native library directory to use; otherwise use "/system/lib/apkname". 5820 String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5821 File lib64 = new File(apkRoot, LIB64_DIR_NAME); 5822 File packLib64 = new File(lib64, apkName); 5823 libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME); 5824 } else { 5825 libDir = mAppLibInstallDir; 5826 } 5827 final String nativeLibraryPath = (new File(libDir, apkName)).getPath(); 5828 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 5829 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 5830 } 5831 5832 // Deduces the required ABI of an upgraded system app. 5833 private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) { 5834 final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir); 5835 final String apkName = getApkName(pkg.applicationInfo.sourceDir); 5836 5837 // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>" 5838 // or similar. 5839 final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath()); 5840 final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath()); 5841 5842 // Assume that the bundled native libraries always correspond to the 5843 // most preferred 32 or 64 bit ABI. 5844 if (lib64.exists()) { 5845 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 5846 pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0]; 5847 } else if (lib.exists()) { 5848 pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 5849 pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0]; 5850 } else { 5851 // This is the case where the app has no native code. 5852 pkg.applicationInfo.cpuAbi = null; 5853 pkgSetting.cpuAbiString = null; 5854 } 5855 } 5856 5857 private static int copyNativeLibrariesForInternalApp(ApkHandle handle, 5858 final File nativeLibraryDir, String[] abiList) throws IOException { 5859 if (!nativeLibraryDir.isDirectory()) { 5860 nativeLibraryDir.delete(); 5861 5862 if (!nativeLibraryDir.mkdir()) { 5863 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 5864 } 5865 5866 try { 5867 Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); 5868 } catch (ErrnoException e) { 5869 throw new IOException("Cannot chmod native library directory " 5870 + nativeLibraryDir.getPath(), e); 5871 } 5872 } else if (!SELinux.restorecon(nativeLibraryDir)) { 5873 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 5874 } 5875 5876 /* 5877 * If this is an internal application or our nativeLibraryPath points to 5878 * the app-lib directory, unpack the libraries if necessary. 5879 */ 5880 int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList); 5881 if (abi >= 0) { 5882 int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle, 5883 nativeLibraryDir, Build.SUPPORTED_ABIS[abi]); 5884 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 5885 return copyRet; 5886 } 5887 } 5888 5889 return abi; 5890 } 5891 5892 private void killApplication(String pkgName, int appId, String reason) { 5893 // Request the ActivityManager to kill the process(only for existing packages) 5894 // so that we do not end up in a confused state while the user is still using the older 5895 // version of the application while the new one gets installed. 5896 IActivityManager am = ActivityManagerNative.getDefault(); 5897 if (am != null) { 5898 try { 5899 am.killApplicationWithAppId(pkgName, appId, reason); 5900 } catch (RemoteException e) { 5901 } 5902 } 5903 } 5904 5905 void removePackageLI(PackageSetting ps, boolean chatty) { 5906 if (DEBUG_INSTALL) { 5907 if (chatty) 5908 Log.d(TAG, "Removing package " + ps.name); 5909 } 5910 5911 // writer 5912 synchronized (mPackages) { 5913 mPackages.remove(ps.name); 5914 if (ps.codePathString != null) { 5915 mAppDirs.remove(ps.codePathString); 5916 } 5917 5918 final PackageParser.Package pkg = ps.pkg; 5919 if (pkg != null) { 5920 cleanPackageDataStructuresLILPw(pkg, chatty); 5921 } 5922 } 5923 } 5924 5925 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 5926 if (DEBUG_INSTALL) { 5927 if (chatty) 5928 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 5929 } 5930 5931 // writer 5932 synchronized (mPackages) { 5933 mPackages.remove(pkg.applicationInfo.packageName); 5934 if (pkg.mPath != null) { 5935 mAppDirs.remove(pkg.mPath); 5936 } 5937 cleanPackageDataStructuresLILPw(pkg, chatty); 5938 } 5939 } 5940 5941 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 5942 int N = pkg.providers.size(); 5943 StringBuilder r = null; 5944 int i; 5945 for (i=0; i<N; i++) { 5946 PackageParser.Provider p = pkg.providers.get(i); 5947 mProviders.removeProvider(p); 5948 if (p.info.authority == null) { 5949 5950 /* There was another ContentProvider with this authority when 5951 * this app was installed so this authority is null, 5952 * Ignore it as we don't have to unregister the provider. 5953 */ 5954 continue; 5955 } 5956 String names[] = p.info.authority.split(";"); 5957 for (int j = 0; j < names.length; j++) { 5958 if (mProvidersByAuthority.get(names[j]) == p) { 5959 mProvidersByAuthority.remove(names[j]); 5960 if (DEBUG_REMOVE) { 5961 if (chatty) 5962 Log.d(TAG, "Unregistered content provider: " + names[j] 5963 + ", className = " + p.info.name + ", isSyncable = " 5964 + p.info.isSyncable); 5965 } 5966 } 5967 } 5968 if (DEBUG_REMOVE && chatty) { 5969 if (r == null) { 5970 r = new StringBuilder(256); 5971 } else { 5972 r.append(' '); 5973 } 5974 r.append(p.info.name); 5975 } 5976 } 5977 if (r != null) { 5978 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 5979 } 5980 5981 N = pkg.services.size(); 5982 r = null; 5983 for (i=0; i<N; i++) { 5984 PackageParser.Service s = pkg.services.get(i); 5985 mServices.removeService(s); 5986 if (chatty) { 5987 if (r == null) { 5988 r = new StringBuilder(256); 5989 } else { 5990 r.append(' '); 5991 } 5992 r.append(s.info.name); 5993 } 5994 } 5995 if (r != null) { 5996 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 5997 } 5998 5999 N = pkg.receivers.size(); 6000 r = null; 6001 for (i=0; i<N; i++) { 6002 PackageParser.Activity a = pkg.receivers.get(i); 6003 mReceivers.removeActivity(a, "receiver"); 6004 if (DEBUG_REMOVE && chatty) { 6005 if (r == null) { 6006 r = new StringBuilder(256); 6007 } else { 6008 r.append(' '); 6009 } 6010 r.append(a.info.name); 6011 } 6012 } 6013 if (r != null) { 6014 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 6015 } 6016 6017 N = pkg.activities.size(); 6018 r = null; 6019 for (i=0; i<N; i++) { 6020 PackageParser.Activity a = pkg.activities.get(i); 6021 mActivities.removeActivity(a, "activity"); 6022 if (DEBUG_REMOVE && chatty) { 6023 if (r == null) { 6024 r = new StringBuilder(256); 6025 } else { 6026 r.append(' '); 6027 } 6028 r.append(a.info.name); 6029 } 6030 } 6031 if (r != null) { 6032 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 6033 } 6034 6035 N = pkg.permissions.size(); 6036 r = null; 6037 for (i=0; i<N; i++) { 6038 PackageParser.Permission p = pkg.permissions.get(i); 6039 BasePermission bp = mSettings.mPermissions.get(p.info.name); 6040 if (bp == null) { 6041 bp = mSettings.mPermissionTrees.get(p.info.name); 6042 } 6043 if (bp != null && bp.perm == p) { 6044 bp.perm = null; 6045 if (DEBUG_REMOVE && chatty) { 6046 if (r == null) { 6047 r = new StringBuilder(256); 6048 } else { 6049 r.append(' '); 6050 } 6051 r.append(p.info.name); 6052 } 6053 } 6054 } 6055 if (r != null) { 6056 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 6057 } 6058 6059 N = pkg.instrumentation.size(); 6060 r = null; 6061 for (i=0; i<N; i++) { 6062 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 6063 mInstrumentation.remove(a.getComponentName()); 6064 if (DEBUG_REMOVE && chatty) { 6065 if (r == null) { 6066 r = new StringBuilder(256); 6067 } else { 6068 r.append(' '); 6069 } 6070 r.append(a.info.name); 6071 } 6072 } 6073 if (r != null) { 6074 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 6075 } 6076 6077 r = null; 6078 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 6079 // Only system apps can hold shared libraries. 6080 if (pkg.libraryNames != null) { 6081 for (i=0; i<pkg.libraryNames.size(); i++) { 6082 String name = pkg.libraryNames.get(i); 6083 SharedLibraryEntry cur = mSharedLibraries.get(name); 6084 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 6085 mSharedLibraries.remove(name); 6086 if (DEBUG_REMOVE && chatty) { 6087 if (r == null) { 6088 r = new StringBuilder(256); 6089 } else { 6090 r.append(' '); 6091 } 6092 r.append(name); 6093 } 6094 } 6095 } 6096 } 6097 } 6098 if (r != null) { 6099 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 6100 } 6101 } 6102 6103 private static final boolean isPackageFilename(String name) { 6104 return name != null && name.endsWith(".apk"); 6105 } 6106 6107 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 6108 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 6109 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 6110 return true; 6111 } 6112 } 6113 return false; 6114 } 6115 6116 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 6117 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 6118 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 6119 6120 private void updatePermissionsLPw(String changingPkg, 6121 PackageParser.Package pkgInfo, int flags) { 6122 // Make sure there are no dangling permission trees. 6123 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 6124 while (it.hasNext()) { 6125 final BasePermission bp = it.next(); 6126 if (bp.packageSetting == null) { 6127 // We may not yet have parsed the package, so just see if 6128 // we still know about its settings. 6129 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6130 } 6131 if (bp.packageSetting == null) { 6132 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 6133 + " from package " + bp.sourcePackage); 6134 it.remove(); 6135 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6136 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6137 Slog.i(TAG, "Removing old permission tree: " + bp.name 6138 + " from package " + bp.sourcePackage); 6139 flags |= UPDATE_PERMISSIONS_ALL; 6140 it.remove(); 6141 } 6142 } 6143 } 6144 6145 // Make sure all dynamic permissions have been assigned to a package, 6146 // and make sure there are no dangling permissions. 6147 it = mSettings.mPermissions.values().iterator(); 6148 while (it.hasNext()) { 6149 final BasePermission bp = it.next(); 6150 if (bp.type == BasePermission.TYPE_DYNAMIC) { 6151 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 6152 + bp.name + " pkg=" + bp.sourcePackage 6153 + " info=" + bp.pendingInfo); 6154 if (bp.packageSetting == null && bp.pendingInfo != null) { 6155 final BasePermission tree = findPermissionTreeLP(bp.name); 6156 if (tree != null && tree.perm != null) { 6157 bp.packageSetting = tree.packageSetting; 6158 bp.perm = new PackageParser.Permission(tree.perm.owner, 6159 new PermissionInfo(bp.pendingInfo)); 6160 bp.perm.info.packageName = tree.perm.info.packageName; 6161 bp.perm.info.name = bp.name; 6162 bp.uid = tree.uid; 6163 } 6164 } 6165 } 6166 if (bp.packageSetting == null) { 6167 // We may not yet have parsed the package, so just see if 6168 // we still know about its settings. 6169 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 6170 } 6171 if (bp.packageSetting == null) { 6172 Slog.w(TAG, "Removing dangling permission: " + bp.name 6173 + " from package " + bp.sourcePackage); 6174 it.remove(); 6175 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 6176 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 6177 Slog.i(TAG, "Removing old permission: " + bp.name 6178 + " from package " + bp.sourcePackage); 6179 flags |= UPDATE_PERMISSIONS_ALL; 6180 it.remove(); 6181 } 6182 } 6183 } 6184 6185 // Now update the permissions for all packages, in particular 6186 // replace the granted permissions of the system packages. 6187 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 6188 for (PackageParser.Package pkg : mPackages.values()) { 6189 if (pkg != pkgInfo) { 6190 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 6191 } 6192 } 6193 } 6194 6195 if (pkgInfo != null) { 6196 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 6197 } 6198 } 6199 6200 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 6201 final PackageSetting ps = (PackageSetting) pkg.mExtras; 6202 if (ps == null) { 6203 return; 6204 } 6205 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 6206 HashSet<String> origPermissions = gp.grantedPermissions; 6207 boolean changedPermission = false; 6208 6209 if (replace) { 6210 ps.permissionsFixed = false; 6211 if (gp == ps) { 6212 origPermissions = new HashSet<String>(gp.grantedPermissions); 6213 gp.grantedPermissions.clear(); 6214 gp.gids = mGlobalGids; 6215 } 6216 } 6217 6218 if (gp.gids == null) { 6219 gp.gids = mGlobalGids; 6220 } 6221 6222 final int N = pkg.requestedPermissions.size(); 6223 for (int i=0; i<N; i++) { 6224 final String name = pkg.requestedPermissions.get(i); 6225 final boolean required = pkg.requestedPermissionsRequired.get(i); 6226 final BasePermission bp = mSettings.mPermissions.get(name); 6227 if (DEBUG_INSTALL) { 6228 if (gp != ps) { 6229 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 6230 } 6231 } 6232 6233 if (bp == null || bp.packageSetting == null) { 6234 Slog.w(TAG, "Unknown permission " + name 6235 + " in package " + pkg.packageName); 6236 continue; 6237 } 6238 6239 final String perm = bp.name; 6240 boolean allowed; 6241 boolean allowedSig = false; 6242 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 6243 if (level == PermissionInfo.PROTECTION_NORMAL 6244 || level == PermissionInfo.PROTECTION_DANGEROUS) { 6245 // We grant a normal or dangerous permission if any of the following 6246 // are true: 6247 // 1) The permission is required 6248 // 2) The permission is optional, but was granted in the past 6249 // 3) The permission is optional, but was requested by an 6250 // app in /system (not /data) 6251 // 6252 // Otherwise, reject the permission. 6253 allowed = (required || origPermissions.contains(perm) 6254 || (isSystemApp(ps) && !isUpdatedSystemApp(ps))); 6255 } else if (bp.packageSetting == null) { 6256 // This permission is invalid; skip it. 6257 allowed = false; 6258 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 6259 allowed = grantSignaturePermission(perm, pkg, bp, origPermissions); 6260 if (allowed) { 6261 allowedSig = true; 6262 } 6263 } else { 6264 allowed = false; 6265 } 6266 if (DEBUG_INSTALL) { 6267 if (gp != ps) { 6268 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 6269 } 6270 } 6271 if (allowed) { 6272 if (!isSystemApp(ps) && ps.permissionsFixed) { 6273 // If this is an existing, non-system package, then 6274 // we can't add any new permissions to it. 6275 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 6276 // Except... if this is a permission that was added 6277 // to the platform (note: need to only do this when 6278 // updating the platform). 6279 allowed = isNewPlatformPermissionForPackage(perm, pkg); 6280 } 6281 } 6282 if (allowed) { 6283 if (!gp.grantedPermissions.contains(perm)) { 6284 changedPermission = true; 6285 gp.grantedPermissions.add(perm); 6286 gp.gids = appendInts(gp.gids, bp.gids); 6287 } else if (!ps.haveGids) { 6288 gp.gids = appendInts(gp.gids, bp.gids); 6289 } 6290 } else { 6291 Slog.w(TAG, "Not granting permission " + perm 6292 + " to package " + pkg.packageName 6293 + " because it was previously installed without"); 6294 } 6295 } else { 6296 if (gp.grantedPermissions.remove(perm)) { 6297 changedPermission = true; 6298 gp.gids = removeInts(gp.gids, bp.gids); 6299 Slog.i(TAG, "Un-granting permission " + perm 6300 + " from package " + pkg.packageName 6301 + " (protectionLevel=" + bp.protectionLevel 6302 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6303 + ")"); 6304 } else { 6305 Slog.w(TAG, "Not granting permission " + perm 6306 + " to package " + pkg.packageName 6307 + " (protectionLevel=" + bp.protectionLevel 6308 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 6309 + ")"); 6310 } 6311 } 6312 } 6313 6314 if ((changedPermission || replace) && !ps.permissionsFixed && 6315 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 6316 // This is the first that we have heard about this package, so the 6317 // permissions we have now selected are fixed until explicitly 6318 // changed. 6319 ps.permissionsFixed = true; 6320 } 6321 ps.haveGids = true; 6322 } 6323 6324 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 6325 boolean allowed = false; 6326 final int NP = PackageParser.NEW_PERMISSIONS.length; 6327 for (int ip=0; ip<NP; ip++) { 6328 final PackageParser.NewPermissionInfo npi 6329 = PackageParser.NEW_PERMISSIONS[ip]; 6330 if (npi.name.equals(perm) 6331 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 6332 allowed = true; 6333 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 6334 + pkg.packageName); 6335 break; 6336 } 6337 } 6338 return allowed; 6339 } 6340 6341 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 6342 BasePermission bp, HashSet<String> origPermissions) { 6343 boolean allowed; 6344 allowed = (compareSignatures( 6345 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 6346 == PackageManager.SIGNATURE_MATCH) 6347 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 6348 == PackageManager.SIGNATURE_MATCH); 6349 if (!allowed && (bp.protectionLevel 6350 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 6351 if (isSystemApp(pkg)) { 6352 // For updated system applications, a system permission 6353 // is granted only if it had been defined by the original application. 6354 if (isUpdatedSystemApp(pkg)) { 6355 final PackageSetting sysPs = mSettings 6356 .getDisabledSystemPkgLPr(pkg.packageName); 6357 final GrantedPermissions origGp = sysPs.sharedUser != null 6358 ? sysPs.sharedUser : sysPs; 6359 6360 if (origGp.grantedPermissions.contains(perm)) { 6361 // If the original was granted this permission, we take 6362 // that grant decision as read and propagate it to the 6363 // update. 6364 allowed = true; 6365 } else { 6366 // The system apk may have been updated with an older 6367 // version of the one on the data partition, but which 6368 // granted a new system permission that it didn't have 6369 // before. In this case we do want to allow the app to 6370 // now get the new permission if the ancestral apk is 6371 // privileged to get it. 6372 if (sysPs.pkg != null && sysPs.isPrivileged()) { 6373 for (int j=0; 6374 j<sysPs.pkg.requestedPermissions.size(); j++) { 6375 if (perm.equals( 6376 sysPs.pkg.requestedPermissions.get(j))) { 6377 allowed = true; 6378 break; 6379 } 6380 } 6381 } 6382 } 6383 } else { 6384 allowed = isPrivilegedApp(pkg); 6385 } 6386 } 6387 } 6388 if (!allowed && (bp.protectionLevel 6389 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 6390 // For development permissions, a development permission 6391 // is granted only if it was already granted. 6392 allowed = origPermissions.contains(perm); 6393 } 6394 return allowed; 6395 } 6396 6397 final class ActivityIntentResolver 6398 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 6399 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6400 boolean defaultOnly, int userId) { 6401 if (!sUserManager.exists(userId)) return null; 6402 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6403 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6404 } 6405 6406 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6407 int userId) { 6408 if (!sUserManager.exists(userId)) return null; 6409 mFlags = flags; 6410 return super.queryIntent(intent, resolvedType, 6411 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6412 } 6413 6414 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6415 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 6416 if (!sUserManager.exists(userId)) return null; 6417 if (packageActivities == null) { 6418 return null; 6419 } 6420 mFlags = flags; 6421 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6422 final int N = packageActivities.size(); 6423 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 6424 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 6425 6426 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 6427 for (int i = 0; i < N; ++i) { 6428 intentFilters = packageActivities.get(i).intents; 6429 if (intentFilters != null && intentFilters.size() > 0) { 6430 PackageParser.ActivityIntentInfo[] array = 6431 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 6432 intentFilters.toArray(array); 6433 listCut.add(array); 6434 } 6435 } 6436 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6437 } 6438 6439 public final void addActivity(PackageParser.Activity a, String type) { 6440 final boolean systemApp = isSystemApp(a.info.applicationInfo); 6441 mActivities.put(a.getComponentName(), a); 6442 if (DEBUG_SHOW_INFO) 6443 Log.v( 6444 TAG, " " + type + " " + 6445 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 6446 if (DEBUG_SHOW_INFO) 6447 Log.v(TAG, " Class=" + a.info.name); 6448 final int NI = a.intents.size(); 6449 for (int j=0; j<NI; j++) { 6450 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6451 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 6452 intent.setPriority(0); 6453 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 6454 + a.className + " with priority > 0, forcing to 0"); 6455 } 6456 if (DEBUG_SHOW_INFO) { 6457 Log.v(TAG, " IntentFilter:"); 6458 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6459 } 6460 if (!intent.debugCheck()) { 6461 Log.w(TAG, "==> For Activity " + a.info.name); 6462 } 6463 addFilter(intent); 6464 } 6465 } 6466 6467 public final void removeActivity(PackageParser.Activity a, String type) { 6468 mActivities.remove(a.getComponentName()); 6469 if (DEBUG_SHOW_INFO) { 6470 Log.v(TAG, " " + type + " " 6471 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 6472 : a.info.name) + ":"); 6473 Log.v(TAG, " Class=" + a.info.name); 6474 } 6475 final int NI = a.intents.size(); 6476 for (int j=0; j<NI; j++) { 6477 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 6478 if (DEBUG_SHOW_INFO) { 6479 Log.v(TAG, " IntentFilter:"); 6480 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6481 } 6482 removeFilter(intent); 6483 } 6484 } 6485 6486 @Override 6487 protected boolean allowFilterResult( 6488 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 6489 ActivityInfo filterAi = filter.activity.info; 6490 for (int i=dest.size()-1; i>=0; i--) { 6491 ActivityInfo destAi = dest.get(i).activityInfo; 6492 if (destAi.name == filterAi.name 6493 && destAi.packageName == filterAi.packageName) { 6494 return false; 6495 } 6496 } 6497 return true; 6498 } 6499 6500 @Override 6501 protected ActivityIntentInfo[] newArray(int size) { 6502 return new ActivityIntentInfo[size]; 6503 } 6504 6505 @Override 6506 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 6507 if (!sUserManager.exists(userId)) return true; 6508 PackageParser.Package p = filter.activity.owner; 6509 if (p != null) { 6510 PackageSetting ps = (PackageSetting)p.mExtras; 6511 if (ps != null) { 6512 // System apps are never considered stopped for purposes of 6513 // filtering, because there may be no way for the user to 6514 // actually re-launch them. 6515 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 6516 && ps.getStopped(userId); 6517 } 6518 } 6519 return false; 6520 } 6521 6522 @Override 6523 protected boolean isPackageForFilter(String packageName, 6524 PackageParser.ActivityIntentInfo info) { 6525 return packageName.equals(info.activity.owner.packageName); 6526 } 6527 6528 @Override 6529 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 6530 int match, int userId) { 6531 if (!sUserManager.exists(userId)) return null; 6532 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 6533 return null; 6534 } 6535 final PackageParser.Activity activity = info.activity; 6536 if (mSafeMode && (activity.info.applicationInfo.flags 6537 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6538 return null; 6539 } 6540 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 6541 if (ps == null) { 6542 return null; 6543 } 6544 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 6545 ps.readUserState(userId), userId); 6546 if (ai == null) { 6547 return null; 6548 } 6549 final ResolveInfo res = new ResolveInfo(); 6550 res.activityInfo = ai; 6551 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6552 res.filter = info; 6553 } 6554 res.priority = info.getPriority(); 6555 res.preferredOrder = activity.owner.mPreferredOrder; 6556 //System.out.println("Result: " + res.activityInfo.className + 6557 // " = " + res.priority); 6558 res.match = match; 6559 res.isDefault = info.hasDefault; 6560 res.labelRes = info.labelRes; 6561 res.nonLocalizedLabel = info.nonLocalizedLabel; 6562 res.icon = info.icon; 6563 res.system = isSystemApp(res.activityInfo.applicationInfo); 6564 return res; 6565 } 6566 6567 @Override 6568 protected void sortResults(List<ResolveInfo> results) { 6569 Collections.sort(results, mResolvePrioritySorter); 6570 } 6571 6572 @Override 6573 protected void dumpFilter(PrintWriter out, String prefix, 6574 PackageParser.ActivityIntentInfo filter) { 6575 out.print(prefix); out.print( 6576 Integer.toHexString(System.identityHashCode(filter.activity))); 6577 out.print(' '); 6578 filter.activity.printComponentShortName(out); 6579 out.print(" filter "); 6580 out.println(Integer.toHexString(System.identityHashCode(filter))); 6581 } 6582 6583// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6584// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6585// final List<ResolveInfo> retList = Lists.newArrayList(); 6586// while (i.hasNext()) { 6587// final ResolveInfo resolveInfo = i.next(); 6588// if (isEnabledLP(resolveInfo.activityInfo)) { 6589// retList.add(resolveInfo); 6590// } 6591// } 6592// return retList; 6593// } 6594 6595 // Keys are String (activity class name), values are Activity. 6596 private final HashMap<ComponentName, PackageParser.Activity> mActivities 6597 = new HashMap<ComponentName, PackageParser.Activity>(); 6598 private int mFlags; 6599 } 6600 6601 private final class ServiceIntentResolver 6602 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 6603 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6604 boolean defaultOnly, int userId) { 6605 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6606 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6607 } 6608 6609 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6610 int userId) { 6611 if (!sUserManager.exists(userId)) return null; 6612 mFlags = flags; 6613 return super.queryIntent(intent, resolvedType, 6614 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6615 } 6616 6617 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6618 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 6619 if (!sUserManager.exists(userId)) return null; 6620 if (packageServices == null) { 6621 return null; 6622 } 6623 mFlags = flags; 6624 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 6625 final int N = packageServices.size(); 6626 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 6627 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 6628 6629 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 6630 for (int i = 0; i < N; ++i) { 6631 intentFilters = packageServices.get(i).intents; 6632 if (intentFilters != null && intentFilters.size() > 0) { 6633 PackageParser.ServiceIntentInfo[] array = 6634 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 6635 intentFilters.toArray(array); 6636 listCut.add(array); 6637 } 6638 } 6639 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6640 } 6641 6642 public final void addService(PackageParser.Service s) { 6643 mServices.put(s.getComponentName(), s); 6644 if (DEBUG_SHOW_INFO) { 6645 Log.v(TAG, " " 6646 + (s.info.nonLocalizedLabel != null 6647 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6648 Log.v(TAG, " Class=" + s.info.name); 6649 } 6650 final int NI = s.intents.size(); 6651 int j; 6652 for (j=0; j<NI; j++) { 6653 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6654 if (DEBUG_SHOW_INFO) { 6655 Log.v(TAG, " IntentFilter:"); 6656 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6657 } 6658 if (!intent.debugCheck()) { 6659 Log.w(TAG, "==> For Service " + s.info.name); 6660 } 6661 addFilter(intent); 6662 } 6663 } 6664 6665 public final void removeService(PackageParser.Service s) { 6666 mServices.remove(s.getComponentName()); 6667 if (DEBUG_SHOW_INFO) { 6668 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 6669 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 6670 Log.v(TAG, " Class=" + s.info.name); 6671 } 6672 final int NI = s.intents.size(); 6673 int j; 6674 for (j=0; j<NI; j++) { 6675 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 6676 if (DEBUG_SHOW_INFO) { 6677 Log.v(TAG, " IntentFilter:"); 6678 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6679 } 6680 removeFilter(intent); 6681 } 6682 } 6683 6684 @Override 6685 protected boolean allowFilterResult( 6686 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 6687 ServiceInfo filterSi = filter.service.info; 6688 for (int i=dest.size()-1; i>=0; i--) { 6689 ServiceInfo destAi = dest.get(i).serviceInfo; 6690 if (destAi.name == filterSi.name 6691 && destAi.packageName == filterSi.packageName) { 6692 return false; 6693 } 6694 } 6695 return true; 6696 } 6697 6698 @Override 6699 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 6700 return new PackageParser.ServiceIntentInfo[size]; 6701 } 6702 6703 @Override 6704 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 6705 if (!sUserManager.exists(userId)) return true; 6706 PackageParser.Package p = filter.service.owner; 6707 if (p != null) { 6708 PackageSetting ps = (PackageSetting)p.mExtras; 6709 if (ps != null) { 6710 // System apps are never considered stopped for purposes of 6711 // filtering, because there may be no way for the user to 6712 // actually re-launch them. 6713 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6714 && ps.getStopped(userId); 6715 } 6716 } 6717 return false; 6718 } 6719 6720 @Override 6721 protected boolean isPackageForFilter(String packageName, 6722 PackageParser.ServiceIntentInfo info) { 6723 return packageName.equals(info.service.owner.packageName); 6724 } 6725 6726 @Override 6727 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 6728 int match, int userId) { 6729 if (!sUserManager.exists(userId)) return null; 6730 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 6731 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 6732 return null; 6733 } 6734 final PackageParser.Service service = info.service; 6735 if (mSafeMode && (service.info.applicationInfo.flags 6736 &ApplicationInfo.FLAG_SYSTEM) == 0) { 6737 return null; 6738 } 6739 PackageSetting ps = (PackageSetting) service.owner.mExtras; 6740 if (ps == null) { 6741 return null; 6742 } 6743 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 6744 ps.readUserState(userId), userId); 6745 if (si == null) { 6746 return null; 6747 } 6748 final ResolveInfo res = new ResolveInfo(); 6749 res.serviceInfo = si; 6750 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 6751 res.filter = filter; 6752 } 6753 res.priority = info.getPriority(); 6754 res.preferredOrder = service.owner.mPreferredOrder; 6755 //System.out.println("Result: " + res.activityInfo.className + 6756 // " = " + res.priority); 6757 res.match = match; 6758 res.isDefault = info.hasDefault; 6759 res.labelRes = info.labelRes; 6760 res.nonLocalizedLabel = info.nonLocalizedLabel; 6761 res.icon = info.icon; 6762 res.system = isSystemApp(res.serviceInfo.applicationInfo); 6763 return res; 6764 } 6765 6766 @Override 6767 protected void sortResults(List<ResolveInfo> results) { 6768 Collections.sort(results, mResolvePrioritySorter); 6769 } 6770 6771 @Override 6772 protected void dumpFilter(PrintWriter out, String prefix, 6773 PackageParser.ServiceIntentInfo filter) { 6774 out.print(prefix); out.print( 6775 Integer.toHexString(System.identityHashCode(filter.service))); 6776 out.print(' '); 6777 filter.service.printComponentShortName(out); 6778 out.print(" filter "); 6779 out.println(Integer.toHexString(System.identityHashCode(filter))); 6780 } 6781 6782// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 6783// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 6784// final List<ResolveInfo> retList = Lists.newArrayList(); 6785// while (i.hasNext()) { 6786// final ResolveInfo resolveInfo = (ResolveInfo) i; 6787// if (isEnabledLP(resolveInfo.serviceInfo)) { 6788// retList.add(resolveInfo); 6789// } 6790// } 6791// return retList; 6792// } 6793 6794 // Keys are String (activity class name), values are Activity. 6795 private final HashMap<ComponentName, PackageParser.Service> mServices 6796 = new HashMap<ComponentName, PackageParser.Service>(); 6797 private int mFlags; 6798 }; 6799 6800 private final class ProviderIntentResolver 6801 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 6802 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 6803 boolean defaultOnly, int userId) { 6804 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 6805 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 6806 } 6807 6808 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 6809 int userId) { 6810 if (!sUserManager.exists(userId)) 6811 return null; 6812 mFlags = flags; 6813 return super.queryIntent(intent, resolvedType, 6814 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 6815 } 6816 6817 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 6818 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 6819 if (!sUserManager.exists(userId)) 6820 return null; 6821 if (packageProviders == null) { 6822 return null; 6823 } 6824 mFlags = flags; 6825 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 6826 final int N = packageProviders.size(); 6827 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 6828 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 6829 6830 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 6831 for (int i = 0; i < N; ++i) { 6832 intentFilters = packageProviders.get(i).intents; 6833 if (intentFilters != null && intentFilters.size() > 0) { 6834 PackageParser.ProviderIntentInfo[] array = 6835 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 6836 intentFilters.toArray(array); 6837 listCut.add(array); 6838 } 6839 } 6840 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 6841 } 6842 6843 public final void addProvider(PackageParser.Provider p) { 6844 mProviders.put(p.getComponentName(), p); 6845 if (DEBUG_SHOW_INFO) { 6846 Log.v(TAG, " " 6847 + (p.info.nonLocalizedLabel != null 6848 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6849 Log.v(TAG, " Class=" + p.info.name); 6850 } 6851 final int NI = p.intents.size(); 6852 int j; 6853 for (j = 0; j < NI; j++) { 6854 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6855 if (DEBUG_SHOW_INFO) { 6856 Log.v(TAG, " IntentFilter:"); 6857 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6858 } 6859 if (!intent.debugCheck()) { 6860 Log.w(TAG, "==> For Provider " + p.info.name); 6861 } 6862 addFilter(intent); 6863 } 6864 } 6865 6866 public final void removeProvider(PackageParser.Provider p) { 6867 mProviders.remove(p.getComponentName()); 6868 if (DEBUG_SHOW_INFO) { 6869 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 6870 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 6871 Log.v(TAG, " Class=" + p.info.name); 6872 } 6873 final int NI = p.intents.size(); 6874 int j; 6875 for (j = 0; j < NI; j++) { 6876 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 6877 if (DEBUG_SHOW_INFO) { 6878 Log.v(TAG, " IntentFilter:"); 6879 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 6880 } 6881 removeFilter(intent); 6882 } 6883 } 6884 6885 @Override 6886 protected boolean allowFilterResult( 6887 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 6888 ProviderInfo filterPi = filter.provider.info; 6889 for (int i = dest.size() - 1; i >= 0; i--) { 6890 ProviderInfo destPi = dest.get(i).providerInfo; 6891 if (destPi.name == filterPi.name 6892 && destPi.packageName == filterPi.packageName) { 6893 return false; 6894 } 6895 } 6896 return true; 6897 } 6898 6899 @Override 6900 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 6901 return new PackageParser.ProviderIntentInfo[size]; 6902 } 6903 6904 @Override 6905 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 6906 if (!sUserManager.exists(userId)) 6907 return true; 6908 PackageParser.Package p = filter.provider.owner; 6909 if (p != null) { 6910 PackageSetting ps = (PackageSetting) p.mExtras; 6911 if (ps != null) { 6912 // System apps are never considered stopped for purposes of 6913 // filtering, because there may be no way for the user to 6914 // actually re-launch them. 6915 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 6916 && ps.getStopped(userId); 6917 } 6918 } 6919 return false; 6920 } 6921 6922 @Override 6923 protected boolean isPackageForFilter(String packageName, 6924 PackageParser.ProviderIntentInfo info) { 6925 return packageName.equals(info.provider.owner.packageName); 6926 } 6927 6928 @Override 6929 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 6930 int match, int userId) { 6931 if (!sUserManager.exists(userId)) 6932 return null; 6933 final PackageParser.ProviderIntentInfo info = filter; 6934 if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) { 6935 return null; 6936 } 6937 final PackageParser.Provider provider = info.provider; 6938 if (mSafeMode && (provider.info.applicationInfo.flags 6939 & ApplicationInfo.FLAG_SYSTEM) == 0) { 6940 return null; 6941 } 6942 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 6943 if (ps == null) { 6944 return null; 6945 } 6946 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 6947 ps.readUserState(userId), userId); 6948 if (pi == null) { 6949 return null; 6950 } 6951 final ResolveInfo res = new ResolveInfo(); 6952 res.providerInfo = pi; 6953 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 6954 res.filter = filter; 6955 } 6956 res.priority = info.getPriority(); 6957 res.preferredOrder = provider.owner.mPreferredOrder; 6958 res.match = match; 6959 res.isDefault = info.hasDefault; 6960 res.labelRes = info.labelRes; 6961 res.nonLocalizedLabel = info.nonLocalizedLabel; 6962 res.icon = info.icon; 6963 res.system = isSystemApp(res.providerInfo.applicationInfo); 6964 return res; 6965 } 6966 6967 @Override 6968 protected void sortResults(List<ResolveInfo> results) { 6969 Collections.sort(results, mResolvePrioritySorter); 6970 } 6971 6972 @Override 6973 protected void dumpFilter(PrintWriter out, String prefix, 6974 PackageParser.ProviderIntentInfo filter) { 6975 out.print(prefix); 6976 out.print( 6977 Integer.toHexString(System.identityHashCode(filter.provider))); 6978 out.print(' '); 6979 filter.provider.printComponentShortName(out); 6980 out.print(" filter "); 6981 out.println(Integer.toHexString(System.identityHashCode(filter))); 6982 } 6983 6984 private final HashMap<ComponentName, PackageParser.Provider> mProviders 6985 = new HashMap<ComponentName, PackageParser.Provider>(); 6986 private int mFlags; 6987 }; 6988 6989 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 6990 new Comparator<ResolveInfo>() { 6991 public int compare(ResolveInfo r1, ResolveInfo r2) { 6992 int v1 = r1.priority; 6993 int v2 = r2.priority; 6994 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 6995 if (v1 != v2) { 6996 return (v1 > v2) ? -1 : 1; 6997 } 6998 v1 = r1.preferredOrder; 6999 v2 = r2.preferredOrder; 7000 if (v1 != v2) { 7001 return (v1 > v2) ? -1 : 1; 7002 } 7003 if (r1.isDefault != r2.isDefault) { 7004 return r1.isDefault ? -1 : 1; 7005 } 7006 v1 = r1.match; 7007 v2 = r2.match; 7008 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 7009 if (v1 != v2) { 7010 return (v1 > v2) ? -1 : 1; 7011 } 7012 if (r1.system != r2.system) { 7013 return r1.system ? -1 : 1; 7014 } 7015 return 0; 7016 } 7017 }; 7018 7019 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 7020 new Comparator<ProviderInfo>() { 7021 public int compare(ProviderInfo p1, ProviderInfo p2) { 7022 final int v1 = p1.initOrder; 7023 final int v2 = p2.initOrder; 7024 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 7025 } 7026 }; 7027 7028 static final void sendPackageBroadcast(String action, String pkg, 7029 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 7030 int[] userIds) { 7031 IActivityManager am = ActivityManagerNative.getDefault(); 7032 if (am != null) { 7033 try { 7034 if (userIds == null) { 7035 userIds = am.getRunningUserIds(); 7036 } 7037 for (int id : userIds) { 7038 final Intent intent = new Intent(action, 7039 pkg != null ? Uri.fromParts("package", pkg, null) : null); 7040 if (extras != null) { 7041 intent.putExtras(extras); 7042 } 7043 if (targetPkg != null) { 7044 intent.setPackage(targetPkg); 7045 } 7046 // Modify the UID when posting to other users 7047 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 7048 if (uid > 0 && UserHandle.getUserId(uid) != id) { 7049 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 7050 intent.putExtra(Intent.EXTRA_UID, uid); 7051 } 7052 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 7053 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 7054 if (DEBUG_BROADCASTS) { 7055 RuntimeException here = new RuntimeException("here"); 7056 here.fillInStackTrace(); 7057 Slog.d(TAG, "Sending to user " + id + ": " 7058 + intent.toShortString(false, true, false, false) 7059 + " " + intent.getExtras(), here); 7060 } 7061 am.broadcastIntent(null, intent, null, finishedReceiver, 7062 0, null, null, null, android.app.AppOpsManager.OP_NONE, 7063 finishedReceiver != null, false, id); 7064 } 7065 } catch (RemoteException ex) { 7066 } 7067 } 7068 } 7069 7070 /** 7071 * Check if the external storage media is available. This is true if there 7072 * is a mounted external storage medium or if the external storage is 7073 * emulated. 7074 */ 7075 private boolean isExternalMediaAvailable() { 7076 return mMediaMounted || Environment.isExternalStorageEmulated(); 7077 } 7078 7079 @Override 7080 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 7081 // writer 7082 synchronized (mPackages) { 7083 if (!isExternalMediaAvailable()) { 7084 // If the external storage is no longer mounted at this point, 7085 // the caller may not have been able to delete all of this 7086 // packages files and can not delete any more. Bail. 7087 return null; 7088 } 7089 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 7090 if (lastPackage != null) { 7091 pkgs.remove(lastPackage); 7092 } 7093 if (pkgs.size() > 0) { 7094 return pkgs.get(0); 7095 } 7096 } 7097 return null; 7098 } 7099 7100 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 7101 if (false) { 7102 RuntimeException here = new RuntimeException("here"); 7103 here.fillInStackTrace(); 7104 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 7105 + " andCode=" + andCode, here); 7106 } 7107 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 7108 userId, andCode ? 1 : 0, packageName)); 7109 } 7110 7111 void startCleaningPackages() { 7112 // reader 7113 synchronized (mPackages) { 7114 if (!isExternalMediaAvailable()) { 7115 return; 7116 } 7117 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 7118 return; 7119 } 7120 } 7121 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 7122 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 7123 IActivityManager am = ActivityManagerNative.getDefault(); 7124 if (am != null) { 7125 try { 7126 am.startService(null, intent, null, UserHandle.USER_OWNER); 7127 } catch (RemoteException e) { 7128 } 7129 } 7130 } 7131 7132 private final class AppDirObserver extends FileObserver { 7133 public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) { 7134 super(path, mask); 7135 mRootDir = path; 7136 mIsRom = isrom; 7137 mIsPrivileged = isPrivileged; 7138 } 7139 7140 public void onEvent(int event, String path) { 7141 String removedPackage = null; 7142 int removedAppId = -1; 7143 int[] removedUsers = null; 7144 String addedPackage = null; 7145 int addedAppId = -1; 7146 int[] addedUsers = null; 7147 7148 // TODO post a message to the handler to obtain serial ordering 7149 synchronized (mInstallLock) { 7150 String fullPathStr = null; 7151 File fullPath = null; 7152 if (path != null) { 7153 fullPath = new File(mRootDir, path); 7154 fullPathStr = fullPath.getPath(); 7155 } 7156 7157 if (DEBUG_APP_DIR_OBSERVER) 7158 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 7159 7160 if (!isPackageFilename(path)) { 7161 if (DEBUG_APP_DIR_OBSERVER) 7162 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 7163 return; 7164 } 7165 7166 // Ignore packages that are being installed or 7167 // have just been installed. 7168 if (ignoreCodePath(fullPathStr)) { 7169 return; 7170 } 7171 PackageParser.Package p = null; 7172 PackageSetting ps = null; 7173 // reader 7174 synchronized (mPackages) { 7175 p = mAppDirs.get(fullPathStr); 7176 if (p != null) { 7177 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 7178 if (ps != null) { 7179 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7180 } else { 7181 removedUsers = sUserManager.getUserIds(); 7182 } 7183 } 7184 addedUsers = sUserManager.getUserIds(); 7185 } 7186 if ((event&REMOVE_EVENTS) != 0) { 7187 if (ps != null) { 7188 if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps); 7189 removePackageLI(ps, true); 7190 removedPackage = ps.name; 7191 removedAppId = ps.appId; 7192 } 7193 } 7194 7195 if ((event&ADD_EVENTS) != 0) { 7196 if (p == null) { 7197 if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath); 7198 int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK; 7199 if (mIsRom) { 7200 flags |= PackageParser.PARSE_IS_SYSTEM 7201 | PackageParser.PARSE_IS_SYSTEM_DIR; 7202 if (mIsPrivileged) { 7203 flags |= PackageParser.PARSE_IS_PRIVILEGED; 7204 } 7205 } 7206 p = scanPackageLI(fullPath, flags, 7207 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 7208 System.currentTimeMillis(), UserHandle.ALL, null); 7209 if (p != null) { 7210 /* 7211 * TODO this seems dangerous as the package may have 7212 * changed since we last acquired the mPackages 7213 * lock. 7214 */ 7215 // writer 7216 synchronized (mPackages) { 7217 updatePermissionsLPw(p.packageName, p, 7218 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 7219 } 7220 addedPackage = p.applicationInfo.packageName; 7221 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 7222 } 7223 } 7224 } 7225 7226 // reader 7227 synchronized (mPackages) { 7228 mSettings.writeLPr(); 7229 } 7230 } 7231 7232 if (removedPackage != null) { 7233 Bundle extras = new Bundle(1); 7234 extras.putInt(Intent.EXTRA_UID, removedAppId); 7235 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 7236 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7237 extras, null, null, removedUsers); 7238 } 7239 if (addedPackage != null) { 7240 Bundle extras = new Bundle(1); 7241 extras.putInt(Intent.EXTRA_UID, addedAppId); 7242 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 7243 extras, null, null, addedUsers); 7244 } 7245 } 7246 7247 private final String mRootDir; 7248 private final boolean mIsRom; 7249 private final boolean mIsPrivileged; 7250 } 7251 7252 /* Called when a downloaded package installation has been confirmed by the user */ 7253 public void installPackage( 7254 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 7255 installPackage(packageURI, observer, flags, null); 7256 } 7257 7258 /* Called when a downloaded package installation has been confirmed by the user */ 7259 @Override 7260 public void installPackage( 7261 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 7262 final String installerPackageName) { 7263 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null, 7264 null, null); 7265 } 7266 7267 @Override 7268 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 7269 int flags, String installerPackageName, Uri verificationURI, 7270 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 7271 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 7272 VerificationParams.NO_UID, manifestDigest); 7273 installPackageWithVerificationAndEncryption(packageURI, observer, flags, 7274 installerPackageName, verificationParams, encryptionParams); 7275 } 7276 7277 @Override 7278 public void installPackageWithVerificationAndEncryption(Uri packageURI, 7279 IPackageInstallObserver observer, int flags, String installerPackageName, 7280 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 7281 installPackageWithVerificationEncryptionAndAbiOverride(packageURI, observer, flags, 7282 installerPackageName, verificationParams, encryptionParams, null); 7283 } 7284 7285 @Override 7286 public void installPackageWithVerificationEncryptionAndAbiOverride(Uri packageURI, 7287 IPackageInstallObserver observer, int flags, String installerPackageName, 7288 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams, 7289 String packageAbiOverride) { 7290 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7291 null); 7292 7293 final int uid = Binder.getCallingUid(); 7294 if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) { 7295 try { 7296 observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED); 7297 } catch (RemoteException re) { 7298 } 7299 return; 7300 } 7301 7302 UserHandle user; 7303 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 7304 user = UserHandle.ALL; 7305 } else { 7306 user = new UserHandle(UserHandle.getUserId(uid)); 7307 } 7308 7309 final int filteredFlags; 7310 7311 if (uid == Process.SHELL_UID || uid == 0) { 7312 if (DEBUG_INSTALL) { 7313 Slog.v(TAG, "Install from ADB"); 7314 } 7315 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 7316 } else { 7317 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 7318 } 7319 7320 verificationParams.setInstallerUid(uid); 7321 7322 final Message msg = mHandler.obtainMessage(INIT_COPY); 7323 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName, 7324 verificationParams, encryptionParams, user, 7325 packageAbiOverride); 7326 mHandler.sendMessage(msg); 7327 } 7328 7329 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) { 7330 Bundle extras = new Bundle(1); 7331 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 7332 7333 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 7334 packageName, extras, null, null, new int[] {userId}); 7335 try { 7336 IActivityManager am = ActivityManagerNative.getDefault(); 7337 final boolean isSystem = 7338 isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 7339 if (isSystem && am.isUserRunning(userId, false)) { 7340 // The just-installed/enabled app is bundled on the system, so presumed 7341 // to be able to run automatically without needing an explicit launch. 7342 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 7343 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 7344 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 7345 .setPackage(packageName); 7346 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 7347 android.app.AppOpsManager.OP_NONE, false, false, userId); 7348 } 7349 } catch (RemoteException e) { 7350 // shouldn't happen 7351 Slog.w(TAG, "Unable to bootstrap installed package", e); 7352 } 7353 } 7354 7355 @Override 7356 public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked, 7357 int userId) { 7358 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7359 PackageSetting pkgSetting; 7360 final int uid = Binder.getCallingUid(); 7361 if (UserHandle.getUserId(uid) != userId) { 7362 mContext.enforceCallingOrSelfPermission( 7363 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7364 "setApplicationBlockedSetting for user " + userId); 7365 } 7366 7367 if (blocked && isPackageDeviceAdmin(packageName, userId)) { 7368 Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin"); 7369 return false; 7370 } 7371 7372 long callingId = Binder.clearCallingIdentity(); 7373 try { 7374 boolean sendAdded = false; 7375 boolean sendRemoved = false; 7376 // writer 7377 synchronized (mPackages) { 7378 pkgSetting = mSettings.mPackages.get(packageName); 7379 if (pkgSetting == null) { 7380 return false; 7381 } 7382 if (pkgSetting.getBlocked(userId) != blocked) { 7383 pkgSetting.setBlocked(blocked, userId); 7384 mSettings.writePackageRestrictionsLPr(userId); 7385 if (blocked) { 7386 sendRemoved = true; 7387 } else { 7388 sendAdded = true; 7389 } 7390 } 7391 } 7392 if (sendAdded) { 7393 sendPackageAddedForUser(packageName, pkgSetting, userId); 7394 return true; 7395 } 7396 if (sendRemoved) { 7397 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 7398 "blocking pkg"); 7399 sendPackageBlockedForUser(packageName, pkgSetting, userId); 7400 } 7401 } finally { 7402 Binder.restoreCallingIdentity(callingId); 7403 } 7404 return false; 7405 } 7406 7407 private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting, 7408 int userId) { 7409 final PackageRemovedInfo info = new PackageRemovedInfo(); 7410 info.removedPackage = packageName; 7411 info.removedUsers = new int[] {userId}; 7412 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 7413 info.sendBroadcast(false, false, false); 7414 } 7415 7416 /** 7417 * Returns true if application is not found or there was an error. Otherwise it returns 7418 * the blocked state of the package for the given user. 7419 */ 7420 @Override 7421 public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) { 7422 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 7423 PackageSetting pkgSetting; 7424 final int uid = Binder.getCallingUid(); 7425 if (UserHandle.getUserId(uid) != userId) { 7426 mContext.enforceCallingPermission( 7427 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7428 "getApplicationBlocked for user " + userId); 7429 } 7430 long callingId = Binder.clearCallingIdentity(); 7431 try { 7432 // writer 7433 synchronized (mPackages) { 7434 pkgSetting = mSettings.mPackages.get(packageName); 7435 if (pkgSetting == null) { 7436 return true; 7437 } 7438 return pkgSetting.getBlocked(userId); 7439 } 7440 } finally { 7441 Binder.restoreCallingIdentity(callingId); 7442 } 7443 } 7444 7445 /** 7446 * @hide 7447 */ 7448 @Override 7449 public int installExistingPackageAsUser(String packageName, int userId) { 7450 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 7451 null); 7452 PackageSetting pkgSetting; 7453 final int uid = Binder.getCallingUid(); 7454 if (UserHandle.getUserId(uid) != userId) { 7455 mContext.enforceCallingPermission( 7456 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 7457 "installExistingPackage for user " + userId); 7458 } 7459 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 7460 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 7461 } 7462 7463 long callingId = Binder.clearCallingIdentity(); 7464 try { 7465 boolean sendAdded = false; 7466 Bundle extras = new Bundle(1); 7467 7468 // writer 7469 synchronized (mPackages) { 7470 pkgSetting = mSettings.mPackages.get(packageName); 7471 if (pkgSetting == null) { 7472 return PackageManager.INSTALL_FAILED_INVALID_URI; 7473 } 7474 if (!pkgSetting.getInstalled(userId)) { 7475 pkgSetting.setInstalled(true, userId); 7476 pkgSetting.setBlocked(false, userId); 7477 mSettings.writePackageRestrictionsLPr(userId); 7478 sendAdded = true; 7479 } 7480 } 7481 7482 if (sendAdded) { 7483 sendPackageAddedForUser(packageName, pkgSetting, userId); 7484 } 7485 } finally { 7486 Binder.restoreCallingIdentity(callingId); 7487 } 7488 7489 return PackageManager.INSTALL_SUCCEEDED; 7490 } 7491 7492 private boolean isUserRestricted(int userId, String restrictionKey) { 7493 Bundle restrictions = sUserManager.getUserRestrictions(userId); 7494 if (restrictions.getBoolean(restrictionKey, false)) { 7495 Log.w(TAG, "User is restricted: " + restrictionKey); 7496 return true; 7497 } 7498 return false; 7499 } 7500 7501 @Override 7502 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 7503 mContext.enforceCallingOrSelfPermission( 7504 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7505 "Only package verification agents can verify applications"); 7506 7507 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7508 final PackageVerificationResponse response = new PackageVerificationResponse( 7509 verificationCode, Binder.getCallingUid()); 7510 msg.arg1 = id; 7511 msg.obj = response; 7512 mHandler.sendMessage(msg); 7513 } 7514 7515 @Override 7516 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 7517 long millisecondsToDelay) { 7518 mContext.enforceCallingOrSelfPermission( 7519 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 7520 "Only package verification agents can extend verification timeouts"); 7521 7522 final PackageVerificationState state = mPendingVerification.get(id); 7523 final PackageVerificationResponse response = new PackageVerificationResponse( 7524 verificationCodeAtTimeout, Binder.getCallingUid()); 7525 7526 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 7527 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 7528 } 7529 if (millisecondsToDelay < 0) { 7530 millisecondsToDelay = 0; 7531 } 7532 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 7533 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 7534 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 7535 } 7536 7537 if ((state != null) && !state.timeoutExtended()) { 7538 state.extendTimeout(); 7539 7540 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 7541 msg.arg1 = id; 7542 msg.obj = response; 7543 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 7544 } 7545 } 7546 7547 private void broadcastPackageVerified(int verificationId, Uri packageUri, 7548 int verificationCode, UserHandle user) { 7549 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 7550 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 7551 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 7552 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 7553 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 7554 7555 mContext.sendBroadcastAsUser(intent, user, 7556 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 7557 } 7558 7559 private ComponentName matchComponentForVerifier(String packageName, 7560 List<ResolveInfo> receivers) { 7561 ActivityInfo targetReceiver = null; 7562 7563 final int NR = receivers.size(); 7564 for (int i = 0; i < NR; i++) { 7565 final ResolveInfo info = receivers.get(i); 7566 if (info.activityInfo == null) { 7567 continue; 7568 } 7569 7570 if (packageName.equals(info.activityInfo.packageName)) { 7571 targetReceiver = info.activityInfo; 7572 break; 7573 } 7574 } 7575 7576 if (targetReceiver == null) { 7577 return null; 7578 } 7579 7580 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 7581 } 7582 7583 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 7584 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 7585 if (pkgInfo.verifiers.length == 0) { 7586 return null; 7587 } 7588 7589 final int N = pkgInfo.verifiers.length; 7590 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 7591 for (int i = 0; i < N; i++) { 7592 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 7593 7594 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 7595 receivers); 7596 if (comp == null) { 7597 continue; 7598 } 7599 7600 final int verifierUid = getUidForVerifier(verifierInfo); 7601 if (verifierUid == -1) { 7602 continue; 7603 } 7604 7605 if (DEBUG_VERIFY) { 7606 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 7607 + " with the correct signature"); 7608 } 7609 sufficientVerifiers.add(comp); 7610 verificationState.addSufficientVerifier(verifierUid); 7611 } 7612 7613 return sufficientVerifiers; 7614 } 7615 7616 private int getUidForVerifier(VerifierInfo verifierInfo) { 7617 synchronized (mPackages) { 7618 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 7619 if (pkg == null) { 7620 return -1; 7621 } else if (pkg.mSignatures.length != 1) { 7622 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7623 + " has more than one signature; ignoring"); 7624 return -1; 7625 } 7626 7627 /* 7628 * If the public key of the package's signature does not match 7629 * our expected public key, then this is a different package and 7630 * we should skip. 7631 */ 7632 7633 final byte[] expectedPublicKey; 7634 try { 7635 final Signature verifierSig = pkg.mSignatures[0]; 7636 final PublicKey publicKey = verifierSig.getPublicKey(); 7637 expectedPublicKey = publicKey.getEncoded(); 7638 } catch (CertificateException e) { 7639 return -1; 7640 } 7641 7642 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 7643 7644 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 7645 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 7646 + " does not have the expected public key; ignoring"); 7647 return -1; 7648 } 7649 7650 return pkg.applicationInfo.uid; 7651 } 7652 } 7653 7654 @Override 7655 public void finishPackageInstall(int token) { 7656 enforceSystemOrRoot("Only the system is allowed to finish installs"); 7657 7658 if (DEBUG_INSTALL) { 7659 Slog.v(TAG, "BM finishing package install for " + token); 7660 } 7661 7662 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7663 mHandler.sendMessage(msg); 7664 } 7665 7666 /** 7667 * Get the verification agent timeout. 7668 * 7669 * @return verification timeout in milliseconds 7670 */ 7671 private long getVerificationTimeout() { 7672 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 7673 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 7674 DEFAULT_VERIFICATION_TIMEOUT); 7675 } 7676 7677 /** 7678 * Get the default verification agent response code. 7679 * 7680 * @return default verification response code 7681 */ 7682 private int getDefaultVerificationResponse() { 7683 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7684 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 7685 DEFAULT_VERIFICATION_RESPONSE); 7686 } 7687 7688 /** 7689 * Check whether or not package verification has been enabled. 7690 * 7691 * @return true if verification should be performed 7692 */ 7693 private boolean isVerificationEnabled(int flags) { 7694 if (!DEFAULT_VERIFY_ENABLE) { 7695 return false; 7696 } 7697 7698 // Check if installing from ADB 7699 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 7700 // Do not run verification in a test harness environment 7701 if (ActivityManager.isRunningInTestHarness()) { 7702 return false; 7703 } 7704 // Check if the developer does not want package verification for ADB installs 7705 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7706 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 7707 return false; 7708 } 7709 } 7710 7711 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7712 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 7713 } 7714 7715 /** 7716 * Get the "allow unknown sources" setting. 7717 * 7718 * @return the current "allow unknown sources" setting 7719 */ 7720 private int getUnknownSourcesSettings() { 7721 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 7722 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 7723 -1); 7724 } 7725 7726 @Override 7727 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 7728 final int uid = Binder.getCallingUid(); 7729 // writer 7730 synchronized (mPackages) { 7731 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 7732 if (targetPackageSetting == null) { 7733 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 7734 } 7735 7736 PackageSetting installerPackageSetting; 7737 if (installerPackageName != null) { 7738 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 7739 if (installerPackageSetting == null) { 7740 throw new IllegalArgumentException("Unknown installer package: " 7741 + installerPackageName); 7742 } 7743 } else { 7744 installerPackageSetting = null; 7745 } 7746 7747 Signature[] callerSignature; 7748 Object obj = mSettings.getUserIdLPr(uid); 7749 if (obj != null) { 7750 if (obj instanceof SharedUserSetting) { 7751 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 7752 } else if (obj instanceof PackageSetting) { 7753 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 7754 } else { 7755 throw new SecurityException("Bad object " + obj + " for uid " + uid); 7756 } 7757 } else { 7758 throw new SecurityException("Unknown calling uid " + uid); 7759 } 7760 7761 // Verify: can't set installerPackageName to a package that is 7762 // not signed with the same cert as the caller. 7763 if (installerPackageSetting != null) { 7764 if (compareSignatures(callerSignature, 7765 installerPackageSetting.signatures.mSignatures) 7766 != PackageManager.SIGNATURE_MATCH) { 7767 throw new SecurityException( 7768 "Caller does not have same cert as new installer package " 7769 + installerPackageName); 7770 } 7771 } 7772 7773 // Verify: if target already has an installer package, it must 7774 // be signed with the same cert as the caller. 7775 if (targetPackageSetting.installerPackageName != null) { 7776 PackageSetting setting = mSettings.mPackages.get( 7777 targetPackageSetting.installerPackageName); 7778 // If the currently set package isn't valid, then it's always 7779 // okay to change it. 7780 if (setting != null) { 7781 if (compareSignatures(callerSignature, 7782 setting.signatures.mSignatures) 7783 != PackageManager.SIGNATURE_MATCH) { 7784 throw new SecurityException( 7785 "Caller does not have same cert as old installer package " 7786 + targetPackageSetting.installerPackageName); 7787 } 7788 } 7789 } 7790 7791 // Okay! 7792 targetPackageSetting.installerPackageName = installerPackageName; 7793 scheduleWriteSettingsLocked(); 7794 } 7795 } 7796 7797 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 7798 // Queue up an async operation since the package installation may take a little while. 7799 mHandler.post(new Runnable() { 7800 public void run() { 7801 mHandler.removeCallbacks(this); 7802 // Result object to be returned 7803 PackageInstalledInfo res = new PackageInstalledInfo(); 7804 res.returnCode = currentStatus; 7805 res.uid = -1; 7806 res.pkg = null; 7807 res.removedInfo = new PackageRemovedInfo(); 7808 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 7809 args.doPreInstall(res.returnCode); 7810 synchronized (mInstallLock) { 7811 installPackageLI(args, true, res); 7812 } 7813 args.doPostInstall(res.returnCode, res.uid); 7814 } 7815 7816 // A restore should be performed at this point if (a) the install 7817 // succeeded, (b) the operation is not an update, and (c) the new 7818 // package has a backupAgent defined. 7819 final boolean update = res.removedInfo.removedPackage != null; 7820 boolean doRestore = (!update 7821 && res.pkg != null 7822 && res.pkg.applicationInfo.backupAgentName != null); 7823 7824 // Set up the post-install work request bookkeeping. This will be used 7825 // and cleaned up by the post-install event handling regardless of whether 7826 // there's a restore pass performed. Token values are >= 1. 7827 int token; 7828 if (mNextInstallToken < 0) mNextInstallToken = 1; 7829 token = mNextInstallToken++; 7830 7831 PostInstallData data = new PostInstallData(args, res); 7832 mRunningInstalls.put(token, data); 7833 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 7834 7835 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 7836 // Pass responsibility to the Backup Manager. It will perform a 7837 // restore if appropriate, then pass responsibility back to the 7838 // Package Manager to run the post-install observer callbacks 7839 // and broadcasts. 7840 IBackupManager bm = IBackupManager.Stub.asInterface( 7841 ServiceManager.getService(Context.BACKUP_SERVICE)); 7842 if (bm != null) { 7843 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 7844 + " to BM for possible restore"); 7845 try { 7846 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 7847 } catch (RemoteException e) { 7848 // can't happen; the backup manager is local 7849 } catch (Exception e) { 7850 Slog.e(TAG, "Exception trying to enqueue restore", e); 7851 doRestore = false; 7852 } 7853 } else { 7854 Slog.e(TAG, "Backup Manager not found!"); 7855 doRestore = false; 7856 } 7857 } 7858 7859 if (!doRestore) { 7860 // No restore possible, or the Backup Manager was mysteriously not 7861 // available -- just fire the post-install work request directly. 7862 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 7863 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 7864 mHandler.sendMessage(msg); 7865 } 7866 } 7867 }); 7868 } 7869 7870 private abstract class HandlerParams { 7871 private static final int MAX_RETRIES = 4; 7872 7873 /** 7874 * Number of times startCopy() has been attempted and had a non-fatal 7875 * error. 7876 */ 7877 private int mRetries = 0; 7878 7879 /** User handle for the user requesting the information or installation. */ 7880 private final UserHandle mUser; 7881 7882 HandlerParams(UserHandle user) { 7883 mUser = user; 7884 } 7885 7886 UserHandle getUser() { 7887 return mUser; 7888 } 7889 7890 final boolean startCopy() { 7891 boolean res; 7892 try { 7893 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 7894 7895 if (++mRetries > MAX_RETRIES) { 7896 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 7897 mHandler.sendEmptyMessage(MCS_GIVE_UP); 7898 handleServiceError(); 7899 return false; 7900 } else { 7901 handleStartCopy(); 7902 res = true; 7903 } 7904 } catch (RemoteException e) { 7905 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 7906 mHandler.sendEmptyMessage(MCS_RECONNECT); 7907 res = false; 7908 } 7909 handleReturnCode(); 7910 return res; 7911 } 7912 7913 final void serviceError() { 7914 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 7915 handleServiceError(); 7916 handleReturnCode(); 7917 } 7918 7919 abstract void handleStartCopy() throws RemoteException; 7920 abstract void handleServiceError(); 7921 abstract void handleReturnCode(); 7922 } 7923 7924 class MeasureParams extends HandlerParams { 7925 private final PackageStats mStats; 7926 private boolean mSuccess; 7927 7928 private final IPackageStatsObserver mObserver; 7929 7930 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 7931 super(new UserHandle(stats.userHandle)); 7932 mObserver = observer; 7933 mStats = stats; 7934 } 7935 7936 @Override 7937 public String toString() { 7938 return "MeasureParams{" 7939 + Integer.toHexString(System.identityHashCode(this)) 7940 + " " + mStats.packageName + "}"; 7941 } 7942 7943 @Override 7944 void handleStartCopy() throws RemoteException { 7945 synchronized (mInstallLock) { 7946 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 7947 } 7948 7949 final boolean mounted; 7950 if (Environment.isExternalStorageEmulated()) { 7951 mounted = true; 7952 } else { 7953 final String status = Environment.getExternalStorageState(); 7954 mounted = (Environment.MEDIA_MOUNTED.equals(status) 7955 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 7956 } 7957 7958 if (mounted) { 7959 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 7960 7961 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 7962 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 7963 7964 mStats.externalDataSize = calculateDirectorySize(mContainerService, 7965 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 7966 7967 // Always subtract cache size, since it's a subdirectory 7968 mStats.externalDataSize -= mStats.externalCacheSize; 7969 7970 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 7971 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 7972 7973 mStats.externalObbSize = calculateDirectorySize(mContainerService, 7974 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 7975 } 7976 } 7977 7978 @Override 7979 void handleReturnCode() { 7980 if (mObserver != null) { 7981 try { 7982 mObserver.onGetStatsCompleted(mStats, mSuccess); 7983 } catch (RemoteException e) { 7984 Slog.i(TAG, "Observer no longer exists."); 7985 } 7986 } 7987 } 7988 7989 @Override 7990 void handleServiceError() { 7991 Slog.e(TAG, "Could not measure application " + mStats.packageName 7992 + " external storage"); 7993 } 7994 } 7995 7996 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 7997 throws RemoteException { 7998 long result = 0; 7999 for (File path : paths) { 8000 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 8001 } 8002 return result; 8003 } 8004 8005 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 8006 for (File path : paths) { 8007 try { 8008 mcs.clearDirectory(path.getAbsolutePath()); 8009 } catch (RemoteException e) { 8010 } 8011 } 8012 } 8013 8014 class InstallParams extends HandlerParams { 8015 final IPackageInstallObserver observer; 8016 int flags; 8017 8018 private final Uri mPackageURI; 8019 final String installerPackageName; 8020 final VerificationParams verificationParams; 8021 private InstallArgs mArgs; 8022 private int mRet; 8023 private File mTempPackage; 8024 final ContainerEncryptionParams encryptionParams; 8025 final String packageAbiOverride; 8026 final String packageInstructionSetOverride; 8027 8028 InstallParams(Uri packageURI, 8029 IPackageInstallObserver observer, int flags, 8030 String installerPackageName, VerificationParams verificationParams, 8031 ContainerEncryptionParams encryptionParams, UserHandle user, 8032 String packageAbiOverride) { 8033 super(user); 8034 this.mPackageURI = packageURI; 8035 this.flags = flags; 8036 this.observer = observer; 8037 this.installerPackageName = installerPackageName; 8038 this.verificationParams = verificationParams; 8039 this.encryptionParams = encryptionParams; 8040 this.packageAbiOverride = packageAbiOverride; 8041 this.packageInstructionSetOverride = (packageAbiOverride == null) ? 8042 packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride); 8043 } 8044 8045 @Override 8046 public String toString() { 8047 return "InstallParams{" 8048 + Integer.toHexString(System.identityHashCode(this)) 8049 + " " + mPackageURI + "}"; 8050 } 8051 8052 public ManifestDigest getManifestDigest() { 8053 if (verificationParams == null) { 8054 return null; 8055 } 8056 return verificationParams.getManifestDigest(); 8057 } 8058 8059 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 8060 String packageName = pkgLite.packageName; 8061 int installLocation = pkgLite.installLocation; 8062 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8063 // reader 8064 synchronized (mPackages) { 8065 PackageParser.Package pkg = mPackages.get(packageName); 8066 if (pkg != null) { 8067 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 8068 // Check for downgrading. 8069 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 8070 if (pkgLite.versionCode < pkg.mVersionCode) { 8071 Slog.w(TAG, "Can't install update of " + packageName 8072 + " update version " + pkgLite.versionCode 8073 + " is older than installed version " 8074 + pkg.mVersionCode); 8075 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 8076 } 8077 } 8078 // Check for updated system application. 8079 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 8080 if (onSd) { 8081 Slog.w(TAG, "Cannot install update to system app on sdcard"); 8082 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 8083 } 8084 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8085 } else { 8086 if (onSd) { 8087 // Install flag overrides everything. 8088 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8089 } 8090 // If current upgrade specifies particular preference 8091 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 8092 // Application explicitly specified internal. 8093 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8094 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 8095 // App explictly prefers external. Let policy decide 8096 } else { 8097 // Prefer previous location 8098 if (isExternal(pkg)) { 8099 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8100 } 8101 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 8102 } 8103 } 8104 } else { 8105 // Invalid install. Return error code 8106 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 8107 } 8108 } 8109 } 8110 // All the special cases have been taken care of. 8111 // Return result based on recommended install location. 8112 if (onSd) { 8113 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 8114 } 8115 return pkgLite.recommendedInstallLocation; 8116 } 8117 8118 private long getMemoryLowThreshold() { 8119 final DeviceStorageMonitorInternal 8120 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8121 if (dsm == null) { 8122 return 0L; 8123 } 8124 return dsm.getMemoryLowThreshold(); 8125 } 8126 8127 /* 8128 * Invoke remote method to get package information and install 8129 * location values. Override install location based on default 8130 * policy if needed and then create install arguments based 8131 * on the install location. 8132 */ 8133 public void handleStartCopy() throws RemoteException { 8134 int ret = PackageManager.INSTALL_SUCCEEDED; 8135 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 8136 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 8137 PackageInfoLite pkgLite = null; 8138 8139 if (onInt && onSd) { 8140 // Check if both bits are set. 8141 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 8142 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8143 } else { 8144 final long lowThreshold = getMemoryLowThreshold(); 8145 if (lowThreshold == 0L) { 8146 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8147 } 8148 8149 try { 8150 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 8151 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8152 8153 final File packageFile; 8154 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 8155 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 8156 if (mTempPackage != null) { 8157 ParcelFileDescriptor out; 8158 try { 8159 out = ParcelFileDescriptor.open(mTempPackage, 8160 ParcelFileDescriptor.MODE_READ_WRITE); 8161 } catch (FileNotFoundException e) { 8162 out = null; 8163 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 8164 } 8165 8166 // Make a temporary file for decryption. 8167 ret = mContainerService 8168 .copyResource(mPackageURI, encryptionParams, out); 8169 IoUtils.closeQuietly(out); 8170 8171 packageFile = mTempPackage; 8172 8173 FileUtils.setPermissions(packageFile.getAbsolutePath(), 8174 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 8175 | FileUtils.S_IROTH, 8176 -1, -1); 8177 } else { 8178 packageFile = null; 8179 } 8180 } else { 8181 packageFile = new File(mPackageURI.getPath()); 8182 } 8183 8184 if (packageFile != null) { 8185 // Remote call to find out default install location 8186 final String packageFilePath = packageFile.getAbsolutePath(); 8187 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 8188 lowThreshold, packageAbiOverride); 8189 8190 /* 8191 * If we have too little free space, try to free cache 8192 * before giving up. 8193 */ 8194 if (pkgLite.recommendedInstallLocation 8195 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8196 final long size = mContainerService.calculateInstalledSize( 8197 packageFilePath, isForwardLocked(), packageAbiOverride); 8198 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 8199 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 8200 flags, lowThreshold, packageAbiOverride); 8201 } 8202 /* 8203 * The cache free must have deleted the file we 8204 * downloaded to install. 8205 * 8206 * TODO: fix the "freeCache" call to not delete 8207 * the file we care about. 8208 */ 8209 if (pkgLite.recommendedInstallLocation 8210 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8211 pkgLite.recommendedInstallLocation 8212 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 8213 } 8214 } 8215 } 8216 } finally { 8217 mContext.revokeUriPermission(mPackageURI, 8218 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8219 } 8220 } 8221 8222 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8223 int loc = pkgLite.recommendedInstallLocation; 8224 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 8225 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 8226 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 8227 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 8228 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 8229 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8230 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 8231 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 8232 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 8233 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 8234 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 8235 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 8236 } else { 8237 // Override with defaults if needed. 8238 loc = installLocationPolicy(pkgLite, flags); 8239 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 8240 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 8241 } else if (!onSd && !onInt) { 8242 // Override install location with flags 8243 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 8244 // Set the flag to install on external media. 8245 flags |= PackageManager.INSTALL_EXTERNAL; 8246 flags &= ~PackageManager.INSTALL_INTERNAL; 8247 } else { 8248 // Make sure the flag for installing on external 8249 // media is unset 8250 flags |= PackageManager.INSTALL_INTERNAL; 8251 flags &= ~PackageManager.INSTALL_EXTERNAL; 8252 } 8253 } 8254 } 8255 } 8256 8257 final InstallArgs args = createInstallArgs(this); 8258 mArgs = args; 8259 8260 if (ret == PackageManager.INSTALL_SUCCEEDED) { 8261 /* 8262 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 8263 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 8264 */ 8265 int userIdentifier = getUser().getIdentifier(); 8266 if (userIdentifier == UserHandle.USER_ALL 8267 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 8268 userIdentifier = UserHandle.USER_OWNER; 8269 } 8270 8271 /* 8272 * Determine if we have any installed package verifiers. If we 8273 * do, then we'll defer to them to verify the packages. 8274 */ 8275 final int requiredUid = mRequiredVerifierPackage == null ? -1 8276 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 8277 if (requiredUid != -1 && isVerificationEnabled(flags)) { 8278 final Intent verification = new Intent( 8279 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 8280 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 8281 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 8282 8283 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 8284 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 8285 0 /* TODO: Which userId? */); 8286 8287 if (DEBUG_VERIFY) { 8288 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 8289 + verification.toString() + " with " + pkgLite.verifiers.length 8290 + " optional verifiers"); 8291 } 8292 8293 final int verificationId = mPendingVerificationToken++; 8294 8295 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 8296 8297 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 8298 installerPackageName); 8299 8300 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 8301 8302 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 8303 pkgLite.packageName); 8304 8305 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 8306 pkgLite.versionCode); 8307 8308 if (verificationParams != null) { 8309 if (verificationParams.getVerificationURI() != null) { 8310 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 8311 verificationParams.getVerificationURI()); 8312 } 8313 if (verificationParams.getOriginatingURI() != null) { 8314 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 8315 verificationParams.getOriginatingURI()); 8316 } 8317 if (verificationParams.getReferrer() != null) { 8318 verification.putExtra(Intent.EXTRA_REFERRER, 8319 verificationParams.getReferrer()); 8320 } 8321 if (verificationParams.getOriginatingUid() >= 0) { 8322 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 8323 verificationParams.getOriginatingUid()); 8324 } 8325 if (verificationParams.getInstallerUid() >= 0) { 8326 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 8327 verificationParams.getInstallerUid()); 8328 } 8329 } 8330 8331 final PackageVerificationState verificationState = new PackageVerificationState( 8332 requiredUid, args); 8333 8334 mPendingVerification.append(verificationId, verificationState); 8335 8336 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 8337 receivers, verificationState); 8338 8339 /* 8340 * If any sufficient verifiers were listed in the package 8341 * manifest, attempt to ask them. 8342 */ 8343 if (sufficientVerifiers != null) { 8344 final int N = sufficientVerifiers.size(); 8345 if (N == 0) { 8346 Slog.i(TAG, "Additional verifiers required, but none installed."); 8347 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 8348 } else { 8349 for (int i = 0; i < N; i++) { 8350 final ComponentName verifierComponent = sufficientVerifiers.get(i); 8351 8352 final Intent sufficientIntent = new Intent(verification); 8353 sufficientIntent.setComponent(verifierComponent); 8354 8355 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 8356 } 8357 } 8358 } 8359 8360 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 8361 mRequiredVerifierPackage, receivers); 8362 if (ret == PackageManager.INSTALL_SUCCEEDED 8363 && mRequiredVerifierPackage != null) { 8364 /* 8365 * Send the intent to the required verification agent, 8366 * but only start the verification timeout after the 8367 * target BroadcastReceivers have run. 8368 */ 8369 verification.setComponent(requiredVerifierComponent); 8370 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 8371 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 8372 new BroadcastReceiver() { 8373 @Override 8374 public void onReceive(Context context, Intent intent) { 8375 final Message msg = mHandler 8376 .obtainMessage(CHECK_PENDING_VERIFICATION); 8377 msg.arg1 = verificationId; 8378 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 8379 } 8380 }, null, 0, null, null); 8381 8382 /* 8383 * We don't want the copy to proceed until verification 8384 * succeeds, so null out this field. 8385 */ 8386 mArgs = null; 8387 } 8388 } else { 8389 /* 8390 * No package verification is enabled, so immediately start 8391 * the remote call to initiate copy using temporary file. 8392 */ 8393 ret = args.copyApk(mContainerService, true); 8394 } 8395 } 8396 8397 mRet = ret; 8398 } 8399 8400 @Override 8401 void handleReturnCode() { 8402 // If mArgs is null, then MCS couldn't be reached. When it 8403 // reconnects, it will try again to install. At that point, this 8404 // will succeed. 8405 if (mArgs != null) { 8406 processPendingInstall(mArgs, mRet); 8407 8408 if (mTempPackage != null) { 8409 if (!mTempPackage.delete()) { 8410 Slog.w(TAG, "Couldn't delete temporary file: " + 8411 mTempPackage.getAbsolutePath()); 8412 } 8413 } 8414 } 8415 } 8416 8417 @Override 8418 void handleServiceError() { 8419 mArgs = createInstallArgs(this); 8420 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8421 } 8422 8423 public boolean isForwardLocked() { 8424 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8425 } 8426 8427 public Uri getPackageUri() { 8428 if (mTempPackage != null) { 8429 return Uri.fromFile(mTempPackage); 8430 } else { 8431 return mPackageURI; 8432 } 8433 } 8434 } 8435 8436 /* 8437 * Utility class used in movePackage api. 8438 * srcArgs and targetArgs are not set for invalid flags and make 8439 * sure to do null checks when invoking methods on them. 8440 * We probably want to return ErrorPrams for both failed installs 8441 * and moves. 8442 */ 8443 class MoveParams extends HandlerParams { 8444 final IPackageMoveObserver observer; 8445 final int flags; 8446 final String packageName; 8447 final InstallArgs srcArgs; 8448 final InstallArgs targetArgs; 8449 int uid; 8450 int mRet; 8451 8452 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 8453 String packageName, String dataDir, String instructionSet, 8454 int uid, UserHandle user) { 8455 super(user); 8456 this.srcArgs = srcArgs; 8457 this.observer = observer; 8458 this.flags = flags; 8459 this.packageName = packageName; 8460 this.uid = uid; 8461 if (srcArgs != null) { 8462 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 8463 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet); 8464 } else { 8465 targetArgs = null; 8466 } 8467 } 8468 8469 @Override 8470 public String toString() { 8471 return "MoveParams{" 8472 + Integer.toHexString(System.identityHashCode(this)) 8473 + " " + packageName + "}"; 8474 } 8475 8476 public void handleStartCopy() throws RemoteException { 8477 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8478 // Check for storage space on target medium 8479 if (!targetArgs.checkFreeStorage(mContainerService)) { 8480 Log.w(TAG, "Insufficient storage to install"); 8481 return; 8482 } 8483 8484 mRet = srcArgs.doPreCopy(); 8485 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8486 return; 8487 } 8488 8489 mRet = targetArgs.copyApk(mContainerService, false); 8490 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8491 srcArgs.doPostCopy(uid); 8492 return; 8493 } 8494 8495 mRet = srcArgs.doPostCopy(uid); 8496 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8497 return; 8498 } 8499 8500 mRet = targetArgs.doPreInstall(mRet); 8501 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 8502 return; 8503 } 8504 8505 if (DEBUG_SD_INSTALL) { 8506 StringBuilder builder = new StringBuilder(); 8507 if (srcArgs != null) { 8508 builder.append("src: "); 8509 builder.append(srcArgs.getCodePath()); 8510 } 8511 if (targetArgs != null) { 8512 builder.append(" target : "); 8513 builder.append(targetArgs.getCodePath()); 8514 } 8515 Log.i(TAG, builder.toString()); 8516 } 8517 } 8518 8519 @Override 8520 void handleReturnCode() { 8521 targetArgs.doPostInstall(mRet, uid); 8522 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 8523 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 8524 currentStatus = PackageManager.MOVE_SUCCEEDED; 8525 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 8526 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 8527 } 8528 processPendingMove(this, currentStatus); 8529 } 8530 8531 @Override 8532 void handleServiceError() { 8533 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8534 } 8535 } 8536 8537 /** 8538 * Used during creation of InstallArgs 8539 * 8540 * @param flags package installation flags 8541 * @return true if should be installed on external storage 8542 */ 8543 private static boolean installOnSd(int flags) { 8544 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 8545 return false; 8546 } 8547 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 8548 return true; 8549 } 8550 return false; 8551 } 8552 8553 /** 8554 * Used during creation of InstallArgs 8555 * 8556 * @param flags package installation flags 8557 * @return true if should be installed as forward locked 8558 */ 8559 private static boolean installForwardLocked(int flags) { 8560 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8561 } 8562 8563 private InstallArgs createInstallArgs(InstallParams params) { 8564 if (installOnSd(params.flags) || params.isForwardLocked()) { 8565 return new AsecInstallArgs(params); 8566 } else { 8567 return new FileInstallArgs(params); 8568 } 8569 } 8570 8571 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 8572 String nativeLibraryPath, String instructionSet) { 8573 final boolean isInAsec; 8574 if (installOnSd(flags)) { 8575 /* Apps on SD card are always in ASEC containers. */ 8576 isInAsec = true; 8577 } else if (installForwardLocked(flags) 8578 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 8579 /* 8580 * Forward-locked apps are only in ASEC containers if they're the 8581 * new style 8582 */ 8583 isInAsec = true; 8584 } else { 8585 isInAsec = false; 8586 } 8587 8588 if (isInAsec) { 8589 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8590 instructionSet, installOnSd(flags), installForwardLocked(flags)); 8591 } else { 8592 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 8593 instructionSet); 8594 } 8595 } 8596 8597 // Used by package mover 8598 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir, 8599 String instructionSet) { 8600 if (installOnSd(flags) || installForwardLocked(flags)) { 8601 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 8602 + AsecInstallArgs.RES_FILE_NAME); 8603 return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags), 8604 installForwardLocked(flags)); 8605 } else { 8606 return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet); 8607 } 8608 } 8609 8610 static abstract class InstallArgs { 8611 final IPackageInstallObserver observer; 8612 // Always refers to PackageManager flags only 8613 final int flags; 8614 final Uri packageURI; 8615 final String installerPackageName; 8616 final ManifestDigest manifestDigest; 8617 final UserHandle user; 8618 final String instructionSet; 8619 final String abiOverride; 8620 8621 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags, 8622 String installerPackageName, ManifestDigest manifestDigest, 8623 UserHandle user, String instructionSet, String abiOverride) { 8624 this.packageURI = packageURI; 8625 this.flags = flags; 8626 this.observer = observer; 8627 this.installerPackageName = installerPackageName; 8628 this.manifestDigest = manifestDigest; 8629 this.user = user; 8630 this.instructionSet = instructionSet; 8631 this.abiOverride = abiOverride; 8632 } 8633 8634 abstract void createCopyFile(); 8635 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 8636 abstract int doPreInstall(int status); 8637 abstract boolean doRename(int status, String pkgName, String oldCodePath); 8638 8639 abstract int doPostInstall(int status, int uid); 8640 abstract String getCodePath(); 8641 abstract String getResourcePath(); 8642 abstract String getNativeLibraryPath(); 8643 // Need installer lock especially for dex file removal. 8644 abstract void cleanUpResourcesLI(); 8645 abstract boolean doPostDeleteLI(boolean delete); 8646 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 8647 8648 /** 8649 * Called before the source arguments are copied. This is used mostly 8650 * for MoveParams when it needs to read the source file to put it in the 8651 * destination. 8652 */ 8653 int doPreCopy() { 8654 return PackageManager.INSTALL_SUCCEEDED; 8655 } 8656 8657 /** 8658 * Called after the source arguments are copied. This is used mostly for 8659 * MoveParams when it needs to read the source file to put it in the 8660 * destination. 8661 * 8662 * @return 8663 */ 8664 int doPostCopy(int uid) { 8665 return PackageManager.INSTALL_SUCCEEDED; 8666 } 8667 8668 protected boolean isFwdLocked() { 8669 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 8670 } 8671 8672 UserHandle getUser() { 8673 return user; 8674 } 8675 } 8676 8677 class FileInstallArgs extends InstallArgs { 8678 File installDir; 8679 String codeFileName; 8680 String resourceFileName; 8681 String libraryPath; 8682 boolean created = false; 8683 8684 FileInstallArgs(InstallParams params) { 8685 super(params.getPackageUri(), params.observer, params.flags, 8686 params.installerPackageName, params.getManifestDigest(), 8687 params.getUser(), params.packageInstructionSetOverride, 8688 params.packageAbiOverride); 8689 } 8690 8691 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 8692 String instructionSet) { 8693 super(null, null, 0, null, null, null, instructionSet, null); 8694 File codeFile = new File(fullCodePath); 8695 installDir = codeFile.getParentFile(); 8696 codeFileName = fullCodePath; 8697 resourceFileName = fullResourcePath; 8698 libraryPath = nativeLibraryPath; 8699 } 8700 8701 FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) { 8702 super(packageURI, null, 0, null, null, null, instructionSet, null); 8703 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8704 String apkName = getNextCodePath(null, pkgName, ".apk"); 8705 codeFileName = new File(installDir, apkName + ".apk").getPath(); 8706 resourceFileName = getResourcePathFromCodePath(); 8707 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 8708 } 8709 8710 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 8711 final long lowThreshold; 8712 8713 final DeviceStorageMonitorInternal 8714 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 8715 if (dsm == null) { 8716 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 8717 lowThreshold = 0L; 8718 } else { 8719 if (dsm.isMemoryLow()) { 8720 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 8721 return false; 8722 } 8723 8724 lowThreshold = dsm.getMemoryLowThreshold(); 8725 } 8726 8727 try { 8728 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8729 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8730 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 8731 } finally { 8732 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8733 } 8734 } 8735 8736 String getCodePath() { 8737 return codeFileName; 8738 } 8739 8740 void createCopyFile() { 8741 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 8742 codeFileName = createTempPackageFile(installDir).getPath(); 8743 resourceFileName = getResourcePathFromCodePath(); 8744 libraryPath = getLibraryPathFromCodePath(); 8745 created = true; 8746 } 8747 8748 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 8749 if (temp) { 8750 // Generate temp file name 8751 createCopyFile(); 8752 } 8753 // Get a ParcelFileDescriptor to write to the output file 8754 File codeFile = new File(codeFileName); 8755 if (!created) { 8756 try { 8757 codeFile.createNewFile(); 8758 // Set permissions 8759 if (!setPermissions()) { 8760 // Failed setting permissions. 8761 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8762 } 8763 } catch (IOException e) { 8764 Slog.w(TAG, "Failed to create file " + codeFile); 8765 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8766 } 8767 } 8768 ParcelFileDescriptor out = null; 8769 try { 8770 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 8771 } catch (FileNotFoundException e) { 8772 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 8773 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8774 } 8775 // Copy the resource now 8776 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8777 try { 8778 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 8779 Intent.FLAG_GRANT_READ_URI_PERMISSION); 8780 ret = imcs.copyResource(packageURI, null, out); 8781 } finally { 8782 IoUtils.closeQuietly(out); 8783 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 8784 } 8785 8786 if (isFwdLocked()) { 8787 final File destResourceFile = new File(getResourcePath()); 8788 8789 // Copy the public files 8790 try { 8791 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 8792 } catch (IOException e) { 8793 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 8794 + " forward-locked app."); 8795 destResourceFile.delete(); 8796 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 8797 } 8798 } 8799 8800 final File nativeLibraryFile = new File(getNativeLibraryPath()); 8801 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 8802 if (nativeLibraryFile.exists()) { 8803 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8804 nativeLibraryFile.delete(); 8805 } 8806 8807 String[] abiList = (abiOverride != null) ? 8808 new String[] { abiOverride } : Build.SUPPORTED_ABIS; 8809 ApkHandle handle = null; 8810 try { 8811 handle = ApkHandle.create(codeFile); 8812 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && 8813 abiOverride == null && 8814 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8815 abiList = Build.SUPPORTED_32_BIT_ABIS; 8816 } 8817 8818 int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList); 8819 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8820 return copyRet; 8821 } 8822 } catch (IOException e) { 8823 Slog.e(TAG, "Copying native libraries failed", e); 8824 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 8825 } finally { 8826 IoUtils.closeQuietly(handle); 8827 } 8828 8829 return ret; 8830 } 8831 8832 int doPreInstall(int status) { 8833 if (status != PackageManager.INSTALL_SUCCEEDED) { 8834 cleanUp(); 8835 } 8836 return status; 8837 } 8838 8839 boolean doRename(int status, final String pkgName, String oldCodePath) { 8840 if (status != PackageManager.INSTALL_SUCCEEDED) { 8841 cleanUp(); 8842 return false; 8843 } else { 8844 final File oldCodeFile = new File(getCodePath()); 8845 final File oldResourceFile = new File(getResourcePath()); 8846 final File oldLibraryFile = new File(getNativeLibraryPath()); 8847 8848 // Rename APK file based on packageName 8849 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 8850 final File newCodeFile = new File(installDir, apkName + ".apk"); 8851 if (!oldCodeFile.renameTo(newCodeFile)) { 8852 return false; 8853 } 8854 codeFileName = newCodeFile.getPath(); 8855 8856 // Rename public resource file if it's forward-locked. 8857 final File newResFile = new File(getResourcePathFromCodePath()); 8858 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 8859 return false; 8860 } 8861 resourceFileName = newResFile.getPath(); 8862 8863 // Rename library path 8864 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 8865 if (newLibraryFile.exists()) { 8866 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 8867 newLibraryFile.delete(); 8868 } 8869 if (!oldLibraryFile.renameTo(newLibraryFile)) { 8870 Slog.e(TAG, "Cannot rename native library directory " 8871 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 8872 return false; 8873 } 8874 libraryPath = newLibraryFile.getPath(); 8875 8876 // Attempt to set permissions 8877 if (!setPermissions()) { 8878 return false; 8879 } 8880 8881 if (!SELinux.restorecon(newCodeFile)) { 8882 return false; 8883 } 8884 8885 return true; 8886 } 8887 } 8888 8889 int doPostInstall(int status, int uid) { 8890 if (status != PackageManager.INSTALL_SUCCEEDED) { 8891 cleanUp(); 8892 } 8893 return status; 8894 } 8895 8896 String getResourcePath() { 8897 return resourceFileName; 8898 } 8899 8900 private String getResourcePathFromCodePath() { 8901 final String codePath = getCodePath(); 8902 if (isFwdLocked()) { 8903 final StringBuilder sb = new StringBuilder(); 8904 8905 sb.append(mAppInstallDir.getPath()); 8906 sb.append('/'); 8907 sb.append(getApkName(codePath)); 8908 sb.append(".zip"); 8909 8910 /* 8911 * If our APK is a temporary file, mark the resource as a 8912 * temporary file as well so it can be cleaned up after 8913 * catastrophic failure. 8914 */ 8915 if (codePath.endsWith(".tmp")) { 8916 sb.append(".tmp"); 8917 } 8918 8919 return sb.toString(); 8920 } else { 8921 return codePath; 8922 } 8923 } 8924 8925 private String getLibraryPathFromCodePath() { 8926 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 8927 } 8928 8929 @Override 8930 String getNativeLibraryPath() { 8931 if (libraryPath == null) { 8932 libraryPath = getLibraryPathFromCodePath(); 8933 } 8934 return libraryPath; 8935 } 8936 8937 private boolean cleanUp() { 8938 boolean ret = true; 8939 String sourceDir = getCodePath(); 8940 String publicSourceDir = getResourcePath(); 8941 if (sourceDir != null) { 8942 File sourceFile = new File(sourceDir); 8943 if (!sourceFile.exists()) { 8944 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 8945 ret = false; 8946 } 8947 // Delete application's code and resources 8948 sourceFile.delete(); 8949 } 8950 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 8951 final File publicSourceFile = new File(publicSourceDir); 8952 if (!publicSourceFile.exists()) { 8953 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 8954 } 8955 if (publicSourceFile.exists()) { 8956 publicSourceFile.delete(); 8957 } 8958 } 8959 8960 if (libraryPath != null) { 8961 File nativeLibraryFile = new File(libraryPath); 8962 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 8963 if (!nativeLibraryFile.delete()) { 8964 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 8965 } 8966 } 8967 8968 return ret; 8969 } 8970 8971 void cleanUpResourcesLI() { 8972 String sourceDir = getCodePath(); 8973 if (cleanUp()) { 8974 if (instructionSet == null) { 8975 throw new IllegalStateException("instructionSet == null"); 8976 } 8977 int retCode = mInstaller.rmdex(sourceDir, instructionSet); 8978 if (retCode < 0) { 8979 Slog.w(TAG, "Couldn't remove dex file for package: " 8980 + " at location " 8981 + sourceDir + ", retcode=" + retCode); 8982 // we don't consider this to be a failure of the core package deletion 8983 } 8984 } 8985 } 8986 8987 private boolean setPermissions() { 8988 // TODO Do this in a more elegant way later on. for now just a hack 8989 if (!isFwdLocked()) { 8990 final int filePermissions = 8991 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 8992 |FileUtils.S_IROTH; 8993 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 8994 if (retCode != 0) { 8995 Slog.e(TAG, "Couldn't set new package file permissions for " + 8996 getCodePath() 8997 + ". The return code was: " + retCode); 8998 // TODO Define new internal error 8999 return false; 9000 } 9001 return true; 9002 } 9003 return true; 9004 } 9005 9006 boolean doPostDeleteLI(boolean delete) { 9007 // XXX err, shouldn't we respect the delete flag? 9008 cleanUpResourcesLI(); 9009 return true; 9010 } 9011 } 9012 9013 private boolean isAsecExternal(String cid) { 9014 final String asecPath = PackageHelper.getSdFilesystem(cid); 9015 return !asecPath.startsWith(mAsecInternalPath); 9016 } 9017 9018 /** 9019 * Extract the MountService "container ID" from the full code path of an 9020 * .apk. 9021 */ 9022 static String cidFromCodePath(String fullCodePath) { 9023 int eidx = fullCodePath.lastIndexOf("/"); 9024 String subStr1 = fullCodePath.substring(0, eidx); 9025 int sidx = subStr1.lastIndexOf("/"); 9026 return subStr1.substring(sidx+1, eidx); 9027 } 9028 9029 class AsecInstallArgs extends InstallArgs { 9030 static final String RES_FILE_NAME = "pkg.apk"; 9031 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 9032 9033 String cid; 9034 String packagePath; 9035 String resourcePath; 9036 String libraryPath; 9037 9038 AsecInstallArgs(InstallParams params) { 9039 super(params.getPackageUri(), params.observer, params.flags, 9040 params.installerPackageName, params.getManifestDigest(), 9041 params.getUser(), params.packageInstructionSetOverride, 9042 params.packageAbiOverride); 9043 } 9044 9045 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 9046 String instructionSet, boolean isExternal, boolean isForwardLocked) { 9047 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9048 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9049 null, null, null, instructionSet, null); 9050 // Extract cid from fullCodePath 9051 int eidx = fullCodePath.lastIndexOf("/"); 9052 String subStr1 = fullCodePath.substring(0, eidx); 9053 int sidx = subStr1.lastIndexOf("/"); 9054 cid = subStr1.substring(sidx+1, eidx); 9055 setCachePath(subStr1); 9056 } 9057 9058 AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) { 9059 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 9060 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9061 null, null, null, instructionSet, null); 9062 this.cid = cid; 9063 setCachePath(PackageHelper.getSdDir(cid)); 9064 } 9065 9066 AsecInstallArgs(Uri packageURI, String cid, String instructionSet, 9067 boolean isExternal, boolean isForwardLocked) { 9068 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 9069 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 9070 null, null, null, instructionSet, null); 9071 this.cid = cid; 9072 } 9073 9074 void createCopyFile() { 9075 cid = getTempContainerId(); 9076 } 9077 9078 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 9079 try { 9080 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9081 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9082 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride); 9083 } finally { 9084 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9085 } 9086 } 9087 9088 private final boolean isExternal() { 9089 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 9090 } 9091 9092 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 9093 if (temp) { 9094 createCopyFile(); 9095 } else { 9096 /* 9097 * Pre-emptively destroy the container since it's destroyed if 9098 * copying fails due to it existing anyway. 9099 */ 9100 PackageHelper.destroySdDir(cid); 9101 } 9102 9103 final String newCachePath; 9104 try { 9105 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 9106 Intent.FLAG_GRANT_READ_URI_PERMISSION); 9107 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 9108 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(), 9109 abiOverride); 9110 } finally { 9111 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 9112 } 9113 9114 if (newCachePath != null) { 9115 setCachePath(newCachePath); 9116 return PackageManager.INSTALL_SUCCEEDED; 9117 } else { 9118 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9119 } 9120 } 9121 9122 @Override 9123 String getCodePath() { 9124 return packagePath; 9125 } 9126 9127 @Override 9128 String getResourcePath() { 9129 return resourcePath; 9130 } 9131 9132 @Override 9133 String getNativeLibraryPath() { 9134 return libraryPath; 9135 } 9136 9137 int doPreInstall(int status) { 9138 if (status != PackageManager.INSTALL_SUCCEEDED) { 9139 // Destroy container 9140 PackageHelper.destroySdDir(cid); 9141 } else { 9142 boolean mounted = PackageHelper.isContainerMounted(cid); 9143 if (!mounted) { 9144 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 9145 Process.SYSTEM_UID); 9146 if (newCachePath != null) { 9147 setCachePath(newCachePath); 9148 } else { 9149 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9150 } 9151 } 9152 } 9153 return status; 9154 } 9155 9156 boolean doRename(int status, final String pkgName, 9157 String oldCodePath) { 9158 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 9159 String newCachePath = null; 9160 if (PackageHelper.isContainerMounted(cid)) { 9161 // Unmount the container 9162 if (!PackageHelper.unMountSdDir(cid)) { 9163 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 9164 return false; 9165 } 9166 } 9167 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9168 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 9169 " which might be stale. Will try to clean up."); 9170 // Clean up the stale container and proceed to recreate. 9171 if (!PackageHelper.destroySdDir(newCacheId)) { 9172 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 9173 return false; 9174 } 9175 // Successfully cleaned up stale container. Try to rename again. 9176 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 9177 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 9178 + " inspite of cleaning it up."); 9179 return false; 9180 } 9181 } 9182 if (!PackageHelper.isContainerMounted(newCacheId)) { 9183 Slog.w(TAG, "Mounting container " + newCacheId); 9184 newCachePath = PackageHelper.mountSdDir(newCacheId, 9185 getEncryptKey(), Process.SYSTEM_UID); 9186 } else { 9187 newCachePath = PackageHelper.getSdDir(newCacheId); 9188 } 9189 if (newCachePath == null) { 9190 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 9191 return false; 9192 } 9193 Log.i(TAG, "Succesfully renamed " + cid + 9194 " to " + newCacheId + 9195 " at new path: " + newCachePath); 9196 cid = newCacheId; 9197 setCachePath(newCachePath); 9198 return true; 9199 } 9200 9201 private void setCachePath(String newCachePath) { 9202 File cachePath = new File(newCachePath); 9203 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 9204 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 9205 9206 if (isFwdLocked()) { 9207 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 9208 } else { 9209 resourcePath = packagePath; 9210 } 9211 } 9212 9213 int doPostInstall(int status, int uid) { 9214 if (status != PackageManager.INSTALL_SUCCEEDED) { 9215 cleanUp(); 9216 } else { 9217 final int groupOwner; 9218 final String protectedFile; 9219 if (isFwdLocked()) { 9220 groupOwner = UserHandle.getSharedAppGid(uid); 9221 protectedFile = RES_FILE_NAME; 9222 } else { 9223 groupOwner = -1; 9224 protectedFile = null; 9225 } 9226 9227 if (uid < Process.FIRST_APPLICATION_UID 9228 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 9229 Slog.e(TAG, "Failed to finalize " + cid); 9230 PackageHelper.destroySdDir(cid); 9231 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9232 } 9233 9234 boolean mounted = PackageHelper.isContainerMounted(cid); 9235 if (!mounted) { 9236 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 9237 } 9238 } 9239 return status; 9240 } 9241 9242 private void cleanUp() { 9243 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 9244 9245 // Destroy secure container 9246 PackageHelper.destroySdDir(cid); 9247 } 9248 9249 void cleanUpResourcesLI() { 9250 String sourceFile = getCodePath(); 9251 // Remove dex file 9252 if (instructionSet == null) { 9253 throw new IllegalStateException("instructionSet == null"); 9254 } 9255 int retCode = mInstaller.rmdex(sourceFile, instructionSet); 9256 if (retCode < 0) { 9257 Slog.w(TAG, "Couldn't remove dex file for package: " 9258 + " at location " 9259 + sourceFile.toString() + ", retcode=" + retCode); 9260 // we don't consider this to be a failure of the core package deletion 9261 } 9262 cleanUp(); 9263 } 9264 9265 boolean matchContainer(String app) { 9266 if (cid.startsWith(app)) { 9267 return true; 9268 } 9269 return false; 9270 } 9271 9272 String getPackageName() { 9273 return getAsecPackageName(cid); 9274 } 9275 9276 boolean doPostDeleteLI(boolean delete) { 9277 boolean ret = false; 9278 boolean mounted = PackageHelper.isContainerMounted(cid); 9279 if (mounted) { 9280 // Unmount first 9281 ret = PackageHelper.unMountSdDir(cid); 9282 } 9283 if (ret && delete) { 9284 cleanUpResourcesLI(); 9285 } 9286 return ret; 9287 } 9288 9289 @Override 9290 int doPreCopy() { 9291 if (isFwdLocked()) { 9292 if (!PackageHelper.fixSdPermissions(cid, 9293 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 9294 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9295 } 9296 } 9297 9298 return PackageManager.INSTALL_SUCCEEDED; 9299 } 9300 9301 @Override 9302 int doPostCopy(int uid) { 9303 if (isFwdLocked()) { 9304 if (uid < Process.FIRST_APPLICATION_UID 9305 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 9306 RES_FILE_NAME)) { 9307 Slog.e(TAG, "Failed to finalize " + cid); 9308 PackageHelper.destroySdDir(cid); 9309 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9310 } 9311 } 9312 9313 return PackageManager.INSTALL_SUCCEEDED; 9314 } 9315 }; 9316 9317 static String getAsecPackageName(String packageCid) { 9318 int idx = packageCid.lastIndexOf("-"); 9319 if (idx == -1) { 9320 return packageCid; 9321 } 9322 return packageCid.substring(0, idx); 9323 } 9324 9325 // Utility method used to create code paths based on package name and available index. 9326 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 9327 String idxStr = ""; 9328 int idx = 1; 9329 // Fall back to default value of idx=1 if prefix is not 9330 // part of oldCodePath 9331 if (oldCodePath != null) { 9332 String subStr = oldCodePath; 9333 // Drop the suffix right away 9334 if (subStr.endsWith(suffix)) { 9335 subStr = subStr.substring(0, subStr.length() - suffix.length()); 9336 } 9337 // If oldCodePath already contains prefix find out the 9338 // ending index to either increment or decrement. 9339 int sidx = subStr.lastIndexOf(prefix); 9340 if (sidx != -1) { 9341 subStr = subStr.substring(sidx + prefix.length()); 9342 if (subStr != null) { 9343 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 9344 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 9345 } 9346 try { 9347 idx = Integer.parseInt(subStr); 9348 if (idx <= 1) { 9349 idx++; 9350 } else { 9351 idx--; 9352 } 9353 } catch(NumberFormatException e) { 9354 } 9355 } 9356 } 9357 } 9358 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 9359 return prefix + idxStr; 9360 } 9361 9362 // Utility method used to ignore ADD/REMOVE events 9363 // by directory observer. 9364 private static boolean ignoreCodePath(String fullPathStr) { 9365 String apkName = getApkName(fullPathStr); 9366 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 9367 if (idx != -1 && ((idx+1) < apkName.length())) { 9368 // Make sure the package ends with a numeral 9369 String version = apkName.substring(idx+1); 9370 try { 9371 Integer.parseInt(version); 9372 return true; 9373 } catch (NumberFormatException e) {} 9374 } 9375 return false; 9376 } 9377 9378 // Utility method that returns the relative package path with respect 9379 // to the installation directory. Like say for /data/data/com.test-1.apk 9380 // string com.test-1 is returned. 9381 static String getApkName(String codePath) { 9382 if (codePath == null) { 9383 return null; 9384 } 9385 int sidx = codePath.lastIndexOf("/"); 9386 int eidx = codePath.lastIndexOf("."); 9387 if (eidx == -1) { 9388 eidx = codePath.length(); 9389 } else if (eidx == 0) { 9390 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 9391 return null; 9392 } 9393 return codePath.substring(sidx+1, eidx); 9394 } 9395 9396 class PackageInstalledInfo { 9397 String name; 9398 int uid; 9399 // The set of users that originally had this package installed. 9400 int[] origUsers; 9401 // The set of users that now have this package installed. 9402 int[] newUsers; 9403 PackageParser.Package pkg; 9404 int returnCode; 9405 PackageRemovedInfo removedInfo; 9406 } 9407 9408 /* 9409 * Install a non-existing package. 9410 */ 9411 private void installNewPackageLI(PackageParser.Package pkg, 9412 int parseFlags, int scanMode, UserHandle user, 9413 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9414 // Remember this for later, in case we need to rollback this install 9415 String pkgName = pkg.packageName; 9416 9417 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 9418 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 9419 synchronized(mPackages) { 9420 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 9421 // A package with the same name is already installed, though 9422 // it has been renamed to an older name. The package we 9423 // are trying to install should be installed as an update to 9424 // the existing one, but that has not been requested, so bail. 9425 Slog.w(TAG, "Attempt to re-install " + pkgName 9426 + " without first uninstalling package running as " 9427 + mSettings.mRenamedPackages.get(pkgName)); 9428 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9429 return; 9430 } 9431 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 9432 // Don't allow installation over an existing package with the same name. 9433 Slog.w(TAG, "Attempt to re-install " + pkgName 9434 + " without first uninstalling."); 9435 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 9436 return; 9437 } 9438 } 9439 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9440 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 9441 System.currentTimeMillis(), user, abiOverride); 9442 if (newPackage == null) { 9443 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9444 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9445 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9446 } 9447 } else { 9448 updateSettingsLI(newPackage, 9449 installerPackageName, 9450 null, null, 9451 res); 9452 // delete the partially installed application. the data directory will have to be 9453 // restored if it was already existing 9454 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9455 // remove package from internal structures. Note that we want deletePackageX to 9456 // delete the package data and cache directories that it created in 9457 // scanPackageLocked, unless those directories existed before we even tried to 9458 // install. 9459 deletePackageLI(pkgName, UserHandle.ALL, false, null, null, 9460 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 9461 res.removedInfo, true); 9462 } 9463 } 9464 } 9465 9466 private void replacePackageLI(PackageParser.Package pkg, 9467 int parseFlags, int scanMode, UserHandle user, 9468 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9469 9470 PackageParser.Package oldPackage; 9471 String pkgName = pkg.packageName; 9472 int[] allUsers; 9473 boolean[] perUserInstalled; 9474 9475 // First find the old package info and check signatures 9476 synchronized(mPackages) { 9477 oldPackage = mPackages.get(pkgName); 9478 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 9479 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 9480 != PackageManager.SIGNATURE_MATCH) { 9481 Slog.w(TAG, "New package has a different signature: " + pkgName); 9482 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 9483 return; 9484 } 9485 9486 // In case of rollback, remember per-user/profile install state 9487 PackageSetting ps = mSettings.mPackages.get(pkgName); 9488 allUsers = sUserManager.getUserIds(); 9489 perUserInstalled = new boolean[allUsers.length]; 9490 for (int i = 0; i < allUsers.length; i++) { 9491 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 9492 } 9493 } 9494 boolean sysPkg = (isSystemApp(oldPackage)); 9495 if (sysPkg) { 9496 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9497 user, allUsers, perUserInstalled, installerPackageName, res, 9498 abiOverride); 9499 } else { 9500 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 9501 user, allUsers, perUserInstalled, installerPackageName, res, 9502 abiOverride); 9503 } 9504 } 9505 9506 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 9507 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9508 int[] allUsers, boolean[] perUserInstalled, 9509 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9510 PackageParser.Package newPackage = null; 9511 String pkgName = deletedPackage.packageName; 9512 boolean deletedPkg = true; 9513 boolean updatedSettings = false; 9514 9515 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 9516 + deletedPackage); 9517 long origUpdateTime; 9518 if (pkg.mExtras != null) { 9519 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 9520 } else { 9521 origUpdateTime = 0; 9522 } 9523 9524 // First delete the existing package while retaining the data directory 9525 if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA, 9526 res.removedInfo, true)) { 9527 // If the existing package wasn't successfully deleted 9528 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9529 deletedPkg = false; 9530 } else { 9531 // Successfully deleted the old package. Now proceed with re-installation 9532 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9533 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 9534 System.currentTimeMillis(), user, abiOverride); 9535 if (newPackage == null) { 9536 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9537 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9538 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9539 } 9540 } else { 9541 updateSettingsLI(newPackage, 9542 installerPackageName, 9543 allUsers, perUserInstalled, 9544 res); 9545 updatedSettings = true; 9546 } 9547 } 9548 9549 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9550 // remove package from internal structures. Note that we want deletePackageX to 9551 // delete the package data and cache directories that it created in 9552 // scanPackageLocked, unless those directories existed before we even tried to 9553 // install. 9554 if(updatedSettings) { 9555 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 9556 deletePackageLI( 9557 pkgName, null, true, allUsers, perUserInstalled, 9558 PackageManager.DELETE_KEEP_DATA, 9559 res.removedInfo, true); 9560 } 9561 // Since we failed to install the new package we need to restore the old 9562 // package that we deleted. 9563 if (deletedPkg) { 9564 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 9565 File restoreFile = new File(deletedPackage.mPath); 9566 // Parse old package 9567 boolean oldOnSd = isExternal(deletedPackage); 9568 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 9569 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 9570 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 9571 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 9572 | SCAN_UPDATE_TIME; 9573 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 9574 origUpdateTime, null, null) == null) { 9575 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 9576 return; 9577 } 9578 // Restore of old package succeeded. Update permissions. 9579 // writer 9580 synchronized (mPackages) { 9581 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 9582 UPDATE_PERMISSIONS_ALL); 9583 // can downgrade to reader 9584 mSettings.writeLPr(); 9585 } 9586 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 9587 } 9588 } 9589 } 9590 9591 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 9592 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 9593 int[] allUsers, boolean[] perUserInstalled, 9594 String installerPackageName, PackageInstalledInfo res, String abiOverride) { 9595 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 9596 + ", old=" + deletedPackage); 9597 PackageParser.Package newPackage = null; 9598 boolean updatedSettings = false; 9599 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 9600 PackageParser.PARSE_IS_SYSTEM; 9601 if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) { 9602 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 9603 } 9604 String packageName = deletedPackage.packageName; 9605 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 9606 if (packageName == null) { 9607 Slog.w(TAG, "Attempt to delete null packageName."); 9608 return; 9609 } 9610 PackageParser.Package oldPkg; 9611 PackageSetting oldPkgSetting; 9612 // reader 9613 synchronized (mPackages) { 9614 oldPkg = mPackages.get(packageName); 9615 oldPkgSetting = mSettings.mPackages.get(packageName); 9616 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 9617 (oldPkgSetting == null)) { 9618 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 9619 return; 9620 } 9621 } 9622 9623 killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg"); 9624 9625 res.removedInfo.uid = oldPkg.applicationInfo.uid; 9626 res.removedInfo.removedPackage = packageName; 9627 // Remove existing system package 9628 removePackageLI(oldPkgSetting, true); 9629 // writer 9630 synchronized (mPackages) { 9631 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 9632 // We didn't need to disable the .apk as a current system package, 9633 // which means we are replacing another update that is already 9634 // installed. We need to make sure to delete the older one's .apk. 9635 res.removedInfo.args = createInstallArgs(0, 9636 deletedPackage.applicationInfo.sourceDir, 9637 deletedPackage.applicationInfo.publicSourceDir, 9638 deletedPackage.applicationInfo.nativeLibraryDir, 9639 getAppInstructionSet(deletedPackage.applicationInfo)); 9640 } else { 9641 res.removedInfo.args = null; 9642 } 9643 } 9644 9645 // Successfully disabled the old package. Now proceed with re-installation 9646 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 9647 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9648 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride); 9649 if (newPackage == null) { 9650 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 9651 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 9652 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 9653 } 9654 } else { 9655 if (newPackage.mExtras != null) { 9656 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 9657 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 9658 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 9659 } 9660 updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res); 9661 updatedSettings = true; 9662 } 9663 9664 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 9665 // Re installation failed. Restore old information 9666 // Remove new pkg information 9667 if (newPackage != null) { 9668 removeInstalledPackageLI(newPackage, true); 9669 } 9670 // Add back the old system package 9671 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null); 9672 // Restore the old system information in Settings 9673 synchronized(mPackages) { 9674 if (updatedSettings) { 9675 mSettings.enableSystemPackageLPw(packageName); 9676 mSettings.setInstallerPackageName(packageName, 9677 oldPkgSetting.installerPackageName); 9678 } 9679 mSettings.writeLPr(); 9680 } 9681 } 9682 } 9683 9684 // Utility method used to move dex files during install. 9685 private int moveDexFilesLI(PackageParser.Package newPackage) { 9686 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 9687 final String instructionSet = getAppInstructionSet(newPackage.applicationInfo); 9688 int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath, 9689 instructionSet); 9690 if (retCode != 0) { 9691 /* 9692 * Programs may be lazily run through dexopt, so the 9693 * source may not exist. However, something seems to 9694 * have gone wrong, so note that dexopt needs to be 9695 * run again and remove the source file. In addition, 9696 * remove the target to make sure there isn't a stale 9697 * file from a previous version of the package. 9698 */ 9699 newPackage.mDexOptNeeded = true; 9700 mInstaller.rmdex(newPackage.mScanPath, instructionSet); 9701 mInstaller.rmdex(newPackage.mPath, instructionSet); 9702 } 9703 } 9704 return PackageManager.INSTALL_SUCCEEDED; 9705 } 9706 9707 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 9708 int[] allUsers, boolean[] perUserInstalled, 9709 PackageInstalledInfo res) { 9710 String pkgName = newPackage.packageName; 9711 synchronized (mPackages) { 9712 //write settings. the installStatus will be incomplete at this stage. 9713 //note that the new package setting would have already been 9714 //added to mPackages. It hasn't been persisted yet. 9715 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 9716 mSettings.writeLPr(); 9717 } 9718 9719 if ((res.returnCode = moveDexFilesLI(newPackage)) 9720 != PackageManager.INSTALL_SUCCEEDED) { 9721 // Discontinue if moving dex files failed. 9722 return; 9723 } 9724 9725 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath); 9726 9727 synchronized (mPackages) { 9728 updatePermissionsLPw(newPackage.packageName, newPackage, 9729 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 9730 ? UPDATE_PERMISSIONS_ALL : 0)); 9731 // For system-bundled packages, we assume that installing an upgraded version 9732 // of the package implies that the user actually wants to run that new code, 9733 // so we enable the package. 9734 if (isSystemApp(newPackage)) { 9735 // NB: implicit assumption that system package upgrades apply to all users 9736 if (DEBUG_INSTALL) { 9737 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 9738 } 9739 PackageSetting ps = mSettings.mPackages.get(pkgName); 9740 if (ps != null) { 9741 if (res.origUsers != null) { 9742 for (int userHandle : res.origUsers) { 9743 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 9744 userHandle, installerPackageName); 9745 } 9746 } 9747 // Also convey the prior install/uninstall state 9748 if (allUsers != null && perUserInstalled != null) { 9749 for (int i = 0; i < allUsers.length; i++) { 9750 if (DEBUG_INSTALL) { 9751 Slog.d(TAG, " user " + allUsers[i] 9752 + " => " + perUserInstalled[i]); 9753 } 9754 ps.setInstalled(perUserInstalled[i], allUsers[i]); 9755 } 9756 // these install state changes will be persisted in the 9757 // upcoming call to mSettings.writeLPr(). 9758 } 9759 } 9760 } 9761 res.name = pkgName; 9762 res.uid = newPackage.applicationInfo.uid; 9763 res.pkg = newPackage; 9764 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 9765 mSettings.setInstallerPackageName(pkgName, installerPackageName); 9766 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9767 //to update install status 9768 mSettings.writeLPr(); 9769 } 9770 } 9771 9772 private void installPackageLI(InstallArgs args, 9773 boolean newInstall, PackageInstalledInfo res) { 9774 int pFlags = args.flags; 9775 String installerPackageName = args.installerPackageName; 9776 File tmpPackageFile = new File(args.getCodePath()); 9777 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 9778 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 9779 boolean replace = false; 9780 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 9781 | (newInstall ? SCAN_NEW_INSTALL : 0); 9782 // Result object to be returned 9783 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 9784 9785 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 9786 // Retrieve PackageSettings and parse package 9787 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 9788 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 9789 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 9790 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 9791 pp.setSeparateProcesses(mSeparateProcesses); 9792 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 9793 null, mMetrics, parseFlags); 9794 if (pkg == null) { 9795 res.returnCode = pp.getParseError(); 9796 return; 9797 } 9798 String pkgName = res.name = pkg.packageName; 9799 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 9800 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 9801 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 9802 return; 9803 } 9804 } 9805 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) { 9806 res.returnCode = pp.getParseError(); 9807 return; 9808 } 9809 9810 /* If the installer passed in a manifest digest, compare it now. */ 9811 if (args.manifestDigest != null) { 9812 if (DEBUG_INSTALL) { 9813 final String parsedManifest = pkg.manifestDigest == null ? "null" 9814 : pkg.manifestDigest.toString(); 9815 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 9816 + parsedManifest); 9817 } 9818 9819 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 9820 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 9821 return; 9822 } 9823 } else if (DEBUG_INSTALL) { 9824 final String parsedManifest = pkg.manifestDigest == null 9825 ? "null" : pkg.manifestDigest.toString(); 9826 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 9827 } 9828 9829 // Get rid of all references to package scan path via parser. 9830 pp = null; 9831 String oldCodePath = null; 9832 boolean systemApp = false; 9833 synchronized (mPackages) { 9834 // Check if installing already existing package 9835 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 9836 String oldName = mSettings.mRenamedPackages.get(pkgName); 9837 if (pkg.mOriginalPackages != null 9838 && pkg.mOriginalPackages.contains(oldName) 9839 && mPackages.containsKey(oldName)) { 9840 // This package is derived from an original package, 9841 // and this device has been updating from that original 9842 // name. We must continue using the original name, so 9843 // rename the new package here. 9844 pkg.setPackageName(oldName); 9845 pkgName = pkg.packageName; 9846 replace = true; 9847 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 9848 + oldName + " pkgName=" + pkgName); 9849 } else if (mPackages.containsKey(pkgName)) { 9850 // This package, under its official name, already exists 9851 // on the device; we should replace it. 9852 replace = true; 9853 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 9854 } 9855 } 9856 PackageSetting ps = mSettings.mPackages.get(pkgName); 9857 if (ps != null) { 9858 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 9859 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 9860 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 9861 systemApp = (ps.pkg.applicationInfo.flags & 9862 ApplicationInfo.FLAG_SYSTEM) != 0; 9863 } 9864 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9865 } 9866 } 9867 9868 if (systemApp && onSd) { 9869 // Disable updates to system apps on sdcard 9870 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 9871 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 9872 return; 9873 } 9874 9875 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 9876 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 9877 return; 9878 } 9879 // Set application objects path explicitly after the rename 9880 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 9881 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 9882 if (replace) { 9883 replacePackageLI(pkg, parseFlags, scanMode, args.user, 9884 installerPackageName, res, args.abiOverride); 9885 } else { 9886 installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user, 9887 installerPackageName, res, args.abiOverride); 9888 } 9889 synchronized (mPackages) { 9890 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9891 if (ps != null) { 9892 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 9893 } 9894 } 9895 } 9896 9897 private static boolean isForwardLocked(PackageParser.Package pkg) { 9898 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9899 } 9900 9901 9902 private boolean isForwardLocked(PackageSetting ps) { 9903 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 9904 } 9905 9906 private static boolean isExternal(PackageParser.Package pkg) { 9907 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9908 } 9909 9910 private static boolean isExternal(PackageSetting ps) { 9911 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 9912 } 9913 9914 private static boolean isSystemApp(PackageParser.Package pkg) { 9915 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9916 } 9917 9918 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 9919 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0; 9920 } 9921 9922 private static boolean isSystemApp(ApplicationInfo info) { 9923 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 9924 } 9925 9926 private static boolean isSystemApp(PackageSetting ps) { 9927 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 9928 } 9929 9930 private static boolean isUpdatedSystemApp(PackageSetting ps) { 9931 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9932 } 9933 9934 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 9935 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 9936 } 9937 9938 private int packageFlagsToInstallFlags(PackageSetting ps) { 9939 int installFlags = 0; 9940 if (isExternal(ps)) { 9941 installFlags |= PackageManager.INSTALL_EXTERNAL; 9942 } 9943 if (isForwardLocked(ps)) { 9944 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9945 } 9946 return installFlags; 9947 } 9948 9949 private void deleteTempPackageFiles() { 9950 final FilenameFilter filter = new FilenameFilter() { 9951 public boolean accept(File dir, String name) { 9952 return name.startsWith("vmdl") && name.endsWith(".tmp"); 9953 } 9954 }; 9955 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 9956 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 9957 } 9958 9959 private static final void deleteTempPackageFilesInDirectory(File directory, 9960 FilenameFilter filter) { 9961 final String[] tmpFilesList = directory.list(filter); 9962 if (tmpFilesList == null) { 9963 return; 9964 } 9965 for (int i = 0; i < tmpFilesList.length; i++) { 9966 final File tmpFile = new File(directory, tmpFilesList[i]); 9967 tmpFile.delete(); 9968 } 9969 } 9970 9971 private File createTempPackageFile(File installDir) { 9972 File tmpPackageFile; 9973 try { 9974 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 9975 } catch (IOException e) { 9976 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 9977 return null; 9978 } 9979 try { 9980 FileUtils.setPermissions( 9981 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 9982 -1, -1); 9983 if (!SELinux.restorecon(tmpPackageFile)) { 9984 return null; 9985 } 9986 } catch (IOException e) { 9987 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 9988 return null; 9989 } 9990 return tmpPackageFile; 9991 } 9992 9993 @Override 9994 public void deletePackageAsUser(final String packageName, 9995 final IPackageDeleteObserver observer, 9996 final int userId, final int flags) { 9997 mContext.enforceCallingOrSelfPermission( 9998 android.Manifest.permission.DELETE_PACKAGES, null); 9999 final int uid = Binder.getCallingUid(); 10000 if (UserHandle.getUserId(uid) != userId) { 10001 mContext.enforceCallingPermission( 10002 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 10003 "deletePackage for user " + userId); 10004 } 10005 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 10006 try { 10007 observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED); 10008 } catch (RemoteException re) { 10009 } 10010 return; 10011 } 10012 10013 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId); 10014 // Queue up an async operation since the package deletion may take a little while. 10015 mHandler.post(new Runnable() { 10016 public void run() { 10017 mHandler.removeCallbacks(this); 10018 final int returnCode = deletePackageX(packageName, userId, flags); 10019 if (observer != null) { 10020 try { 10021 observer.packageDeleted(packageName, returnCode); 10022 } catch (RemoteException e) { 10023 Log.i(TAG, "Observer no longer exists."); 10024 } //end catch 10025 } //end if 10026 } //end run 10027 }); 10028 } 10029 10030 private boolean isPackageDeviceAdmin(String packageName, int userId) { 10031 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 10032 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 10033 try { 10034 if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId) 10035 || dpm.isDeviceOwner(packageName))) { 10036 return true; 10037 } 10038 } catch (RemoteException e) { 10039 } 10040 return false; 10041 } 10042 10043 /** 10044 * This method is an internal method that could be get invoked either 10045 * to delete an installed package or to clean up a failed installation. 10046 * After deleting an installed package, a broadcast is sent to notify any 10047 * listeners that the package has been installed. For cleaning up a failed 10048 * installation, the broadcast is not necessary since the package's 10049 * installation wouldn't have sent the initial broadcast either 10050 * The key steps in deleting a package are 10051 * deleting the package information in internal structures like mPackages, 10052 * deleting the packages base directories through installd 10053 * updating mSettings to reflect current status 10054 * persisting settings for later use 10055 * sending a broadcast if necessary 10056 */ 10057 private int deletePackageX(String packageName, int userId, int flags) { 10058 final PackageRemovedInfo info = new PackageRemovedInfo(); 10059 final boolean res; 10060 10061 if (isPackageDeviceAdmin(packageName, userId)) { 10062 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 10063 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 10064 } 10065 10066 boolean removedForAllUsers = false; 10067 boolean systemUpdate = false; 10068 10069 // for the uninstall-updates case and restricted profiles, remember the per- 10070 // userhandle installed state 10071 int[] allUsers; 10072 boolean[] perUserInstalled; 10073 synchronized (mPackages) { 10074 PackageSetting ps = mSettings.mPackages.get(packageName); 10075 allUsers = sUserManager.getUserIds(); 10076 perUserInstalled = new boolean[allUsers.length]; 10077 for (int i = 0; i < allUsers.length; i++) { 10078 perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false; 10079 } 10080 } 10081 10082 synchronized (mInstallLock) { 10083 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 10084 res = deletePackageLI(packageName, 10085 (flags & PackageManager.DELETE_ALL_USERS) != 0 10086 ? UserHandle.ALL : new UserHandle(userId), 10087 true, allUsers, perUserInstalled, 10088 flags | REMOVE_CHATTY, info, true); 10089 systemUpdate = info.isRemovedPackageSystemUpdate; 10090 if (res && !systemUpdate && mPackages.get(packageName) == null) { 10091 removedForAllUsers = true; 10092 } 10093 if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate 10094 + " removedForAllUsers=" + removedForAllUsers); 10095 } 10096 10097 if (res) { 10098 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 10099 10100 // If the removed package was a system update, the old system package 10101 // was re-enabled; we need to broadcast this information 10102 if (systemUpdate) { 10103 Bundle extras = new Bundle(1); 10104 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 10105 ? info.removedAppId : info.uid); 10106 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10107 10108 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 10109 extras, null, null, null); 10110 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 10111 extras, null, null, null); 10112 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 10113 null, packageName, null, null); 10114 } 10115 } 10116 // Force a gc here. 10117 Runtime.getRuntime().gc(); 10118 // Delete the resources here after sending the broadcast to let 10119 // other processes clean up before deleting resources. 10120 if (info.args != null) { 10121 synchronized (mInstallLock) { 10122 info.args.doPostDeleteLI(true); 10123 } 10124 } 10125 10126 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 10127 } 10128 10129 static class PackageRemovedInfo { 10130 String removedPackage; 10131 int uid = -1; 10132 int removedAppId = -1; 10133 int[] removedUsers = null; 10134 boolean isRemovedPackageSystemUpdate = false; 10135 // Clean up resources deleted packages. 10136 InstallArgs args = null; 10137 10138 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 10139 Bundle extras = new Bundle(1); 10140 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 10141 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 10142 if (replacing) { 10143 extras.putBoolean(Intent.EXTRA_REPLACING, true); 10144 } 10145 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 10146 if (removedPackage != null) { 10147 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 10148 extras, null, null, removedUsers); 10149 if (fullRemove && !replacing) { 10150 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 10151 extras, null, null, removedUsers); 10152 } 10153 } 10154 if (removedAppId >= 0) { 10155 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 10156 removedUsers); 10157 } 10158 } 10159 } 10160 10161 /* 10162 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 10163 * flag is not set, the data directory is removed as well. 10164 * make sure this flag is set for partially installed apps. If not its meaningless to 10165 * delete a partially installed application. 10166 */ 10167 private void removePackageDataLI(PackageSetting ps, 10168 int[] allUserHandles, boolean[] perUserInstalled, 10169 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 10170 String packageName = ps.name; 10171 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 10172 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 10173 // Retrieve object to delete permissions for shared user later on 10174 final PackageSetting deletedPs; 10175 // reader 10176 synchronized (mPackages) { 10177 deletedPs = mSettings.mPackages.get(packageName); 10178 if (outInfo != null) { 10179 outInfo.removedPackage = packageName; 10180 outInfo.removedUsers = deletedPs != null 10181 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 10182 : null; 10183 } 10184 } 10185 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10186 removeDataDirsLI(packageName); 10187 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 10188 } 10189 // writer 10190 synchronized (mPackages) { 10191 if (deletedPs != null) { 10192 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 10193 if (outInfo != null) { 10194 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 10195 } 10196 if (deletedPs != null) { 10197 updatePermissionsLPw(deletedPs.name, null, 0); 10198 if (deletedPs.sharedUser != null) { 10199 // remove permissions associated with package 10200 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 10201 } 10202 } 10203 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 10204 } 10205 // make sure to preserve per-user disabled state if this removal was just 10206 // a downgrade of a system app to the factory package 10207 if (allUserHandles != null && perUserInstalled != null) { 10208 if (DEBUG_REMOVE) { 10209 Slog.d(TAG, "Propagating install state across downgrade"); 10210 } 10211 for (int i = 0; i < allUserHandles.length; i++) { 10212 if (DEBUG_REMOVE) { 10213 Slog.d(TAG, " user " + allUserHandles[i] 10214 + " => " + perUserInstalled[i]); 10215 } 10216 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10217 } 10218 } 10219 } 10220 // can downgrade to reader 10221 if (writeSettings) { 10222 // Save settings now 10223 mSettings.writeLPr(); 10224 } 10225 } 10226 if (outInfo != null) { 10227 // A user ID was deleted here. Go through all users and remove it 10228 // from KeyStore. 10229 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 10230 } 10231 } 10232 10233 static boolean locationIsPrivileged(File path) { 10234 try { 10235 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 10236 .getCanonicalPath(); 10237 return path.getCanonicalPath().startsWith(privilegedAppDir); 10238 } catch (IOException e) { 10239 Slog.e(TAG, "Unable to access code path " + path); 10240 } 10241 return false; 10242 } 10243 10244 /* 10245 * Tries to delete system package. 10246 */ 10247 private boolean deleteSystemPackageLI(PackageSetting newPs, 10248 int[] allUserHandles, boolean[] perUserInstalled, 10249 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 10250 final boolean applyUserRestrictions 10251 = (allUserHandles != null) && (perUserInstalled != null); 10252 PackageSetting disabledPs = null; 10253 // Confirm if the system package has been updated 10254 // An updated system app can be deleted. This will also have to restore 10255 // the system pkg from system partition 10256 // reader 10257 synchronized (mPackages) { 10258 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 10259 } 10260 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs 10261 + " disabledPs=" + disabledPs); 10262 if (disabledPs == null) { 10263 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 10264 return false; 10265 } else if (DEBUG_REMOVE) { 10266 Slog.d(TAG, "Deleting system pkg from data partition"); 10267 } 10268 if (DEBUG_REMOVE) { 10269 if (applyUserRestrictions) { 10270 Slog.d(TAG, "Remembering install states:"); 10271 for (int i = 0; i < allUserHandles.length; i++) { 10272 Slog.d(TAG, " u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]); 10273 } 10274 } 10275 } 10276 // Delete the updated package 10277 outInfo.isRemovedPackageSystemUpdate = true; 10278 if (disabledPs.versionCode < newPs.versionCode) { 10279 // Delete data for downgrades 10280 flags &= ~PackageManager.DELETE_KEEP_DATA; 10281 } else { 10282 // Preserve data by setting flag 10283 flags |= PackageManager.DELETE_KEEP_DATA; 10284 } 10285 boolean ret = deleteInstalledPackageLI(newPs, true, flags, 10286 allUserHandles, perUserInstalled, outInfo, writeSettings); 10287 if (!ret) { 10288 return false; 10289 } 10290 // writer 10291 synchronized (mPackages) { 10292 // Reinstate the old system package 10293 mSettings.enableSystemPackageLPw(newPs.name); 10294 // Remove any native libraries from the upgraded package. 10295 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 10296 } 10297 // Install the system package 10298 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 10299 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 10300 if (locationIsPrivileged(disabledPs.codePath)) { 10301 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 10302 } 10303 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 10304 parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null); 10305 10306 if (newPkg == null) { 10307 Slog.w(TAG, "Failed to restore system package:" + newPs.name 10308 + " with error:" + mLastScanError); 10309 return false; 10310 } 10311 // writer 10312 synchronized (mPackages) { 10313 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 10314 setInternalAppNativeLibraryPath(newPkg, ps); 10315 updatePermissionsLPw(newPkg.packageName, newPkg, 10316 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 10317 if (applyUserRestrictions) { 10318 if (DEBUG_REMOVE) { 10319 Slog.d(TAG, "Propagating install state across reinstall"); 10320 } 10321 for (int i = 0; i < allUserHandles.length; i++) { 10322 if (DEBUG_REMOVE) { 10323 Slog.d(TAG, " user " + allUserHandles[i] 10324 + " => " + perUserInstalled[i]); 10325 } 10326 ps.setInstalled(perUserInstalled[i], allUserHandles[i]); 10327 } 10328 // Regardless of writeSettings we need to ensure that this restriction 10329 // state propagation is persisted 10330 mSettings.writeAllUsersPackageRestrictionsLPr(); 10331 } 10332 // can downgrade to reader here 10333 if (writeSettings) { 10334 mSettings.writeLPr(); 10335 } 10336 } 10337 return true; 10338 } 10339 10340 private boolean deleteInstalledPackageLI(PackageSetting ps, 10341 boolean deleteCodeAndResources, int flags, 10342 int[] allUserHandles, boolean[] perUserInstalled, 10343 PackageRemovedInfo outInfo, boolean writeSettings) { 10344 if (outInfo != null) { 10345 outInfo.uid = ps.appId; 10346 } 10347 10348 // Delete package data from internal structures and also remove data if flag is set 10349 removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings); 10350 10351 // Delete application code and resources 10352 if (deleteCodeAndResources && (outInfo != null)) { 10353 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 10354 ps.resourcePathString, ps.nativeLibraryPathString, 10355 getAppInstructionSetFromSettings(ps)); 10356 } 10357 return true; 10358 } 10359 10360 /* 10361 * This method handles package deletion in general 10362 */ 10363 private boolean deletePackageLI(String packageName, UserHandle user, 10364 boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled, 10365 int flags, PackageRemovedInfo outInfo, 10366 boolean writeSettings) { 10367 if (packageName == null) { 10368 Slog.w(TAG, "Attempt to delete null packageName."); 10369 return false; 10370 } 10371 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 10372 PackageSetting ps; 10373 boolean dataOnly = false; 10374 int removeUser = -1; 10375 int appId = -1; 10376 synchronized (mPackages) { 10377 ps = mSettings.mPackages.get(packageName); 10378 if (ps == null) { 10379 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10380 return false; 10381 } 10382 if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 10383 && user.getIdentifier() != UserHandle.USER_ALL) { 10384 // The caller is asking that the package only be deleted for a single 10385 // user. To do this, we just mark its uninstalled state and delete 10386 // its data. If this is a system app, we only allow this to happen if 10387 // they have set the special DELETE_SYSTEM_APP which requests different 10388 // semantics than normal for uninstalling system apps. 10389 if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user"); 10390 ps.setUserState(user.getIdentifier(), 10391 COMPONENT_ENABLED_STATE_DEFAULT, 10392 false, //installed 10393 true, //stopped 10394 true, //notLaunched 10395 false, //blocked 10396 null, null, null); 10397 if (!isSystemApp(ps)) { 10398 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 10399 // Other user still have this package installed, so all 10400 // we need to do is clear this user's data and save that 10401 // it is uninstalled. 10402 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 10403 removeUser = user.getIdentifier(); 10404 appId = ps.appId; 10405 mSettings.writePackageRestrictionsLPr(removeUser); 10406 } else { 10407 // We need to set it back to 'installed' so the uninstall 10408 // broadcasts will be sent correctly. 10409 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 10410 ps.setInstalled(true, user.getIdentifier()); 10411 } 10412 } else { 10413 // This is a system app, so we assume that the 10414 // other users still have this package installed, so all 10415 // we need to do is clear this user's data and save that 10416 // it is uninstalled. 10417 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 10418 removeUser = user.getIdentifier(); 10419 appId = ps.appId; 10420 mSettings.writePackageRestrictionsLPr(removeUser); 10421 } 10422 } 10423 } 10424 10425 if (removeUser >= 0) { 10426 // From above, we determined that we are deleting this only 10427 // for a single user. Continue the work here. 10428 if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser); 10429 if (outInfo != null) { 10430 outInfo.removedPackage = packageName; 10431 outInfo.removedAppId = appId; 10432 outInfo.removedUsers = new int[] {removeUser}; 10433 } 10434 mInstaller.clearUserData(packageName, removeUser); 10435 removeKeystoreDataIfNeeded(removeUser, appId); 10436 schedulePackageCleaning(packageName, removeUser, false); 10437 return true; 10438 } 10439 10440 if (dataOnly) { 10441 // Delete application data first 10442 if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only"); 10443 removePackageDataLI(ps, null, null, outInfo, flags, writeSettings); 10444 return true; 10445 } 10446 10447 boolean ret = false; 10448 mSettings.mKeySetManager.removeAppKeySetData(packageName); 10449 if (isSystemApp(ps)) { 10450 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name); 10451 // When an updated system application is deleted we delete the existing resources as well and 10452 // fall back to existing code in system partition 10453 ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled, 10454 flags, outInfo, writeSettings); 10455 } else { 10456 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name); 10457 // Kill application pre-emptively especially for apps on sd. 10458 killApplication(packageName, ps.appId, "uninstall pkg"); 10459 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, 10460 allUserHandles, perUserInstalled, 10461 outInfo, writeSettings); 10462 } 10463 10464 return ret; 10465 } 10466 10467 private final class ClearStorageConnection implements ServiceConnection { 10468 IMediaContainerService mContainerService; 10469 10470 @Override 10471 public void onServiceConnected(ComponentName name, IBinder service) { 10472 synchronized (this) { 10473 mContainerService = IMediaContainerService.Stub.asInterface(service); 10474 notifyAll(); 10475 } 10476 } 10477 10478 @Override 10479 public void onServiceDisconnected(ComponentName name) { 10480 } 10481 } 10482 10483 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 10484 final boolean mounted; 10485 if (Environment.isExternalStorageEmulated()) { 10486 mounted = true; 10487 } else { 10488 final String status = Environment.getExternalStorageState(); 10489 10490 mounted = status.equals(Environment.MEDIA_MOUNTED) 10491 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 10492 } 10493 10494 if (!mounted) { 10495 return; 10496 } 10497 10498 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 10499 int[] users; 10500 if (userId == UserHandle.USER_ALL) { 10501 users = sUserManager.getUserIds(); 10502 } else { 10503 users = new int[] { userId }; 10504 } 10505 final ClearStorageConnection conn = new ClearStorageConnection(); 10506 if (mContext.bindServiceAsUser( 10507 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) { 10508 try { 10509 for (int curUser : users) { 10510 long timeout = SystemClock.uptimeMillis() + 5000; 10511 synchronized (conn) { 10512 long now = SystemClock.uptimeMillis(); 10513 while (conn.mContainerService == null && now < timeout) { 10514 try { 10515 conn.wait(timeout - now); 10516 } catch (InterruptedException e) { 10517 } 10518 } 10519 } 10520 if (conn.mContainerService == null) { 10521 return; 10522 } 10523 10524 final UserEnvironment userEnv = new UserEnvironment(curUser); 10525 clearDirectory(conn.mContainerService, 10526 userEnv.buildExternalStorageAppCacheDirs(packageName)); 10527 if (allData) { 10528 clearDirectory(conn.mContainerService, 10529 userEnv.buildExternalStorageAppDataDirs(packageName)); 10530 clearDirectory(conn.mContainerService, 10531 userEnv.buildExternalStorageAppMediaDirs(packageName)); 10532 } 10533 } 10534 } finally { 10535 mContext.unbindService(conn); 10536 } 10537 } 10538 } 10539 10540 @Override 10541 public void clearApplicationUserData(final String packageName, 10542 final IPackageDataObserver observer, final int userId) { 10543 mContext.enforceCallingOrSelfPermission( 10544 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 10545 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 10546 // Queue up an async operation since the package deletion may take a little while. 10547 mHandler.post(new Runnable() { 10548 public void run() { 10549 mHandler.removeCallbacks(this); 10550 final boolean succeeded; 10551 synchronized (mInstallLock) { 10552 succeeded = clearApplicationUserDataLI(packageName, userId); 10553 } 10554 clearExternalStorageDataSync(packageName, userId, true); 10555 if (succeeded) { 10556 // invoke DeviceStorageMonitor's update method to clear any notifications 10557 DeviceStorageMonitorInternal 10558 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 10559 if (dsm != null) { 10560 dsm.checkMemory(); 10561 } 10562 } 10563 if(observer != null) { 10564 try { 10565 observer.onRemoveCompleted(packageName, succeeded); 10566 } catch (RemoteException e) { 10567 Log.i(TAG, "Observer no longer exists."); 10568 } 10569 } //end if observer 10570 } //end run 10571 }); 10572 } 10573 10574 private boolean clearApplicationUserDataLI(String packageName, int userId) { 10575 if (packageName == null) { 10576 Slog.w(TAG, "Attempt to delete null packageName."); 10577 return false; 10578 } 10579 PackageParser.Package p; 10580 boolean dataOnly = false; 10581 final int appId; 10582 synchronized (mPackages) { 10583 p = mPackages.get(packageName); 10584 if (p == null) { 10585 dataOnly = true; 10586 PackageSetting ps = mSettings.mPackages.get(packageName); 10587 if ((ps == null) || (ps.pkg == null)) { 10588 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10589 return false; 10590 } 10591 p = ps.pkg; 10592 } 10593 if (!dataOnly) { 10594 // need to check this only for fully installed applications 10595 if (p == null) { 10596 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 10597 return false; 10598 } 10599 final ApplicationInfo applicationInfo = p.applicationInfo; 10600 if (applicationInfo == null) { 10601 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10602 return false; 10603 } 10604 } 10605 if (p != null && p.applicationInfo != null) { 10606 appId = p.applicationInfo.uid; 10607 } else { 10608 appId = -1; 10609 } 10610 } 10611 int retCode = mInstaller.clearUserData(packageName, userId); 10612 if (retCode < 0) { 10613 Slog.w(TAG, "Couldn't remove cache files for package: " 10614 + packageName); 10615 return false; 10616 } 10617 removeKeystoreDataIfNeeded(userId, appId); 10618 return true; 10619 } 10620 10621 /** 10622 * Remove entries from the keystore daemon. Will only remove it if the 10623 * {@code appId} is valid. 10624 */ 10625 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 10626 if (appId < 0) { 10627 return; 10628 } 10629 10630 final KeyStore keyStore = KeyStore.getInstance(); 10631 if (keyStore != null) { 10632 if (userId == UserHandle.USER_ALL) { 10633 for (final int individual : sUserManager.getUserIds()) { 10634 keyStore.clearUid(UserHandle.getUid(individual, appId)); 10635 } 10636 } else { 10637 keyStore.clearUid(UserHandle.getUid(userId, appId)); 10638 } 10639 } else { 10640 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 10641 } 10642 } 10643 10644 @Override 10645 public void deleteApplicationCacheFiles(final String packageName, 10646 final IPackageDataObserver observer) { 10647 mContext.enforceCallingOrSelfPermission( 10648 android.Manifest.permission.DELETE_CACHE_FILES, null); 10649 // Queue up an async operation since the package deletion may take a little while. 10650 final int userId = UserHandle.getCallingUserId(); 10651 mHandler.post(new Runnable() { 10652 public void run() { 10653 mHandler.removeCallbacks(this); 10654 final boolean succeded; 10655 synchronized (mInstallLock) { 10656 succeded = deleteApplicationCacheFilesLI(packageName, userId); 10657 } 10658 clearExternalStorageDataSync(packageName, userId, false); 10659 if(observer != null) { 10660 try { 10661 observer.onRemoveCompleted(packageName, succeded); 10662 } catch (RemoteException e) { 10663 Log.i(TAG, "Observer no longer exists."); 10664 } 10665 } //end if observer 10666 } //end run 10667 }); 10668 } 10669 10670 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 10671 if (packageName == null) { 10672 Slog.w(TAG, "Attempt to delete null packageName."); 10673 return false; 10674 } 10675 PackageParser.Package p; 10676 synchronized (mPackages) { 10677 p = mPackages.get(packageName); 10678 } 10679 if (p == null) { 10680 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10681 return false; 10682 } 10683 final ApplicationInfo applicationInfo = p.applicationInfo; 10684 if (applicationInfo == null) { 10685 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10686 return false; 10687 } 10688 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 10689 if (retCode < 0) { 10690 Slog.w(TAG, "Couldn't remove cache files for package: " 10691 + packageName + " u" + userId); 10692 return false; 10693 } 10694 return true; 10695 } 10696 10697 @Override 10698 public void getPackageSizeInfo(final String packageName, int userHandle, 10699 final IPackageStatsObserver observer) { 10700 mContext.enforceCallingOrSelfPermission( 10701 android.Manifest.permission.GET_PACKAGE_SIZE, null); 10702 10703 PackageStats stats = new PackageStats(packageName, userHandle); 10704 10705 /* 10706 * Queue up an async operation since the package measurement may take a 10707 * little while. 10708 */ 10709 Message msg = mHandler.obtainMessage(INIT_COPY); 10710 msg.obj = new MeasureParams(stats, observer); 10711 mHandler.sendMessage(msg); 10712 } 10713 10714 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 10715 PackageStats pStats) { 10716 if (packageName == null) { 10717 Slog.w(TAG, "Attempt to get size of null packageName."); 10718 return false; 10719 } 10720 PackageParser.Package p; 10721 boolean dataOnly = false; 10722 String libDirPath = null; 10723 String asecPath = null; 10724 PackageSetting ps = null; 10725 synchronized (mPackages) { 10726 p = mPackages.get(packageName); 10727 ps = mSettings.mPackages.get(packageName); 10728 if(p == null) { 10729 dataOnly = true; 10730 if((ps == null) || (ps.pkg == null)) { 10731 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 10732 return false; 10733 } 10734 p = ps.pkg; 10735 } 10736 if (ps != null) { 10737 libDirPath = ps.nativeLibraryPathString; 10738 } 10739 if (p != null && (isExternal(p) || isForwardLocked(p))) { 10740 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 10741 if (secureContainerId != null) { 10742 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 10743 } 10744 } 10745 } 10746 String publicSrcDir = null; 10747 if(!dataOnly) { 10748 final ApplicationInfo applicationInfo = p.applicationInfo; 10749 if (applicationInfo == null) { 10750 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 10751 return false; 10752 } 10753 if (isForwardLocked(p)) { 10754 publicSrcDir = applicationInfo.publicSourceDir; 10755 } 10756 } 10757 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath, 10758 publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps), 10759 pStats); 10760 if (res < 0) { 10761 return false; 10762 } 10763 10764 // Fix-up for forward-locked applications in ASEC containers. 10765 if (!isExternal(p)) { 10766 pStats.codeSize += pStats.externalCodeSize; 10767 pStats.externalCodeSize = 0L; 10768 } 10769 10770 return true; 10771 } 10772 10773 10774 @Override 10775 public void addPackageToPreferred(String packageName) { 10776 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 10777 } 10778 10779 @Override 10780 public void removePackageFromPreferred(String packageName) { 10781 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 10782 } 10783 10784 @Override 10785 public List<PackageInfo> getPreferredPackages(int flags) { 10786 return new ArrayList<PackageInfo>(); 10787 } 10788 10789 private int getUidTargetSdkVersionLockedLPr(int uid) { 10790 Object obj = mSettings.getUserIdLPr(uid); 10791 if (obj instanceof SharedUserSetting) { 10792 final SharedUserSetting sus = (SharedUserSetting) obj; 10793 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 10794 final Iterator<PackageSetting> it = sus.packages.iterator(); 10795 while (it.hasNext()) { 10796 final PackageSetting ps = it.next(); 10797 if (ps.pkg != null) { 10798 int v = ps.pkg.applicationInfo.targetSdkVersion; 10799 if (v < vers) vers = v; 10800 } 10801 } 10802 return vers; 10803 } else if (obj instanceof PackageSetting) { 10804 final PackageSetting ps = (PackageSetting) obj; 10805 if (ps.pkg != null) { 10806 return ps.pkg.applicationInfo.targetSdkVersion; 10807 } 10808 } 10809 return Build.VERSION_CODES.CUR_DEVELOPMENT; 10810 } 10811 10812 @Override 10813 public void addPreferredActivity(IntentFilter filter, int match, 10814 ComponentName[] set, ComponentName activity, int userId) { 10815 addPreferredActivityInternal(filter, match, set, activity, true, userId); 10816 } 10817 10818 private void addPreferredActivityInternal(IntentFilter filter, int match, 10819 ComponentName[] set, ComponentName activity, boolean always, int userId) { 10820 // writer 10821 int callingUid = Binder.getCallingUid(); 10822 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 10823 if (filter.countActions() == 0) { 10824 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 10825 return; 10826 } 10827 synchronized (mPackages) { 10828 if (mContext.checkCallingOrSelfPermission( 10829 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10830 != PackageManager.PERMISSION_GRANTED) { 10831 if (getUidTargetSdkVersionLockedLPr(callingUid) 10832 < Build.VERSION_CODES.FROYO) { 10833 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 10834 + callingUid); 10835 return; 10836 } 10837 mContext.enforceCallingOrSelfPermission( 10838 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10839 } 10840 10841 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 10842 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10843 mSettings.editPreferredActivitiesLPw(userId).addFilter( 10844 new PreferredActivity(filter, match, set, activity, always)); 10845 mSettings.writePackageRestrictionsLPr(userId); 10846 } 10847 } 10848 10849 @Override 10850 public void replacePreferredActivity(IntentFilter filter, int match, 10851 ComponentName[] set, ComponentName activity) { 10852 if (filter.countActions() != 1) { 10853 throw new IllegalArgumentException( 10854 "replacePreferredActivity expects filter to have only 1 action."); 10855 } 10856 if (filter.countDataAuthorities() != 0 10857 || filter.countDataPaths() != 0 10858 || filter.countDataSchemes() > 1 10859 || filter.countDataTypes() != 0) { 10860 throw new IllegalArgumentException( 10861 "replacePreferredActivity expects filter to have no data authorities, " + 10862 "paths, or types; and at most one scheme."); 10863 } 10864 synchronized (mPackages) { 10865 if (mContext.checkCallingOrSelfPermission( 10866 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10867 != PackageManager.PERMISSION_GRANTED) { 10868 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10869 < Build.VERSION_CODES.FROYO) { 10870 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 10871 + Binder.getCallingUid()); 10872 return; 10873 } 10874 mContext.enforceCallingOrSelfPermission( 10875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10876 } 10877 10878 final int callingUserId = UserHandle.getCallingUserId(); 10879 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 10880 if (pir != null) { 10881 Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0)); 10882 if (filter.countDataSchemes() == 1) { 10883 Uri.Builder builder = new Uri.Builder(); 10884 builder.scheme(filter.getDataScheme(0)); 10885 intent.setData(builder.build()); 10886 } 10887 List<PreferredActivity> matches = pir.queryIntent( 10888 intent, null, true, callingUserId); 10889 if (DEBUG_PREFERRED) { 10890 Slog.i(TAG, matches.size() + " preferred matches for " + intent); 10891 } 10892 for (int i = 0; i < matches.size(); i++) { 10893 PreferredActivity pa = matches.get(i); 10894 if (DEBUG_PREFERRED) { 10895 Slog.i(TAG, "Removing preferred activity " 10896 + pa.mPref.mComponent + ":"); 10897 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 10898 } 10899 pir.removeFilter(pa); 10900 } 10901 } 10902 addPreferredActivityInternal(filter, match, set, activity, true, callingUserId); 10903 } 10904 } 10905 10906 @Override 10907 public void clearPackagePreferredActivities(String packageName) { 10908 final int uid = Binder.getCallingUid(); 10909 // writer 10910 synchronized (mPackages) { 10911 PackageParser.Package pkg = mPackages.get(packageName); 10912 if (pkg == null || pkg.applicationInfo.uid != uid) { 10913 if (mContext.checkCallingOrSelfPermission( 10914 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 10915 != PackageManager.PERMISSION_GRANTED) { 10916 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 10917 < Build.VERSION_CODES.FROYO) { 10918 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 10919 + Binder.getCallingUid()); 10920 return; 10921 } 10922 mContext.enforceCallingOrSelfPermission( 10923 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10924 } 10925 } 10926 10927 int user = UserHandle.getCallingUserId(); 10928 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 10929 mSettings.writePackageRestrictionsLPr(user); 10930 scheduleWriteSettingsLocked(); 10931 } 10932 } 10933 } 10934 10935 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 10936 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 10937 ArrayList<PreferredActivity> removed = null; 10938 boolean changed = false; 10939 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 10940 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 10941 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 10942 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 10943 continue; 10944 } 10945 Iterator<PreferredActivity> it = pir.filterIterator(); 10946 while (it.hasNext()) { 10947 PreferredActivity pa = it.next(); 10948 // Mark entry for removal only if it matches the package name 10949 // and the entry is of type "always". 10950 if (packageName == null || 10951 (pa.mPref.mComponent.getPackageName().equals(packageName) 10952 && pa.mPref.mAlways)) { 10953 if (removed == null) { 10954 removed = new ArrayList<PreferredActivity>(); 10955 } 10956 removed.add(pa); 10957 } 10958 } 10959 if (removed != null) { 10960 for (int j=0; j<removed.size(); j++) { 10961 PreferredActivity pa = removed.get(j); 10962 pir.removeFilter(pa); 10963 } 10964 changed = true; 10965 } 10966 } 10967 return changed; 10968 } 10969 10970 @Override 10971 public void resetPreferredActivities(int userId) { 10972 mContext.enforceCallingOrSelfPermission( 10973 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 10974 // writer 10975 synchronized (mPackages) { 10976 int user = UserHandle.getCallingUserId(); 10977 clearPackagePreferredActivitiesLPw(null, user); 10978 mSettings.readDefaultPreferredAppsLPw(this, user); 10979 mSettings.writePackageRestrictionsLPr(user); 10980 scheduleWriteSettingsLocked(); 10981 } 10982 } 10983 10984 @Override 10985 public int getPreferredActivities(List<IntentFilter> outFilters, 10986 List<ComponentName> outActivities, String packageName) { 10987 10988 int num = 0; 10989 final int userId = UserHandle.getCallingUserId(); 10990 // reader 10991 synchronized (mPackages) { 10992 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 10993 if (pir != null) { 10994 final Iterator<PreferredActivity> it = pir.filterIterator(); 10995 while (it.hasNext()) { 10996 final PreferredActivity pa = it.next(); 10997 if (packageName == null 10998 || (pa.mPref.mComponent.getPackageName().equals(packageName) 10999 && pa.mPref.mAlways)) { 11000 if (outFilters != null) { 11001 outFilters.add(new IntentFilter(pa)); 11002 } 11003 if (outActivities != null) { 11004 outActivities.add(pa.mPref.mComponent); 11005 } 11006 } 11007 } 11008 } 11009 } 11010 11011 return num; 11012 } 11013 11014 @Override 11015 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 11016 Intent intent = new Intent(Intent.ACTION_MAIN); 11017 intent.addCategory(Intent.CATEGORY_HOME); 11018 11019 final int callingUserId = UserHandle.getCallingUserId(); 11020 List<ResolveInfo> list = queryIntentActivities(intent, null, 11021 PackageManager.GET_META_DATA, callingUserId); 11022 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 11023 true, false, false, callingUserId); 11024 11025 allHomeCandidates.clear(); 11026 if (list != null) { 11027 for (ResolveInfo ri : list) { 11028 allHomeCandidates.add(ri); 11029 } 11030 } 11031 return (preferred == null || preferred.activityInfo == null) 11032 ? null 11033 : new ComponentName(preferred.activityInfo.packageName, 11034 preferred.activityInfo.name); 11035 } 11036 11037 @Override 11038 public void setApplicationEnabledSetting(String appPackageName, 11039 int newState, int flags, int userId, String callingPackage) { 11040 if (!sUserManager.exists(userId)) return; 11041 if (callingPackage == null) { 11042 callingPackage = Integer.toString(Binder.getCallingUid()); 11043 } 11044 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 11045 } 11046 11047 @Override 11048 public void setComponentEnabledSetting(ComponentName componentName, 11049 int newState, int flags, int userId) { 11050 if (!sUserManager.exists(userId)) return; 11051 setEnabledSetting(componentName.getPackageName(), 11052 componentName.getClassName(), newState, flags, userId, null); 11053 } 11054 11055 private void setEnabledSetting(final String packageName, String className, int newState, 11056 final int flags, int userId, String callingPackage) { 11057 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 11058 || newState == COMPONENT_ENABLED_STATE_ENABLED 11059 || newState == COMPONENT_ENABLED_STATE_DISABLED 11060 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 11061 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 11062 throw new IllegalArgumentException("Invalid new component state: " 11063 + newState); 11064 } 11065 PackageSetting pkgSetting; 11066 final int uid = Binder.getCallingUid(); 11067 final int permission = mContext.checkCallingOrSelfPermission( 11068 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11069 enforceCrossUserPermission(uid, userId, false, "set enabled"); 11070 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11071 boolean sendNow = false; 11072 boolean isApp = (className == null); 11073 String componentName = isApp ? packageName : className; 11074 int packageUid = -1; 11075 ArrayList<String> components; 11076 11077 // writer 11078 synchronized (mPackages) { 11079 pkgSetting = mSettings.mPackages.get(packageName); 11080 if (pkgSetting == null) { 11081 if (className == null) { 11082 throw new IllegalArgumentException( 11083 "Unknown package: " + packageName); 11084 } 11085 throw new IllegalArgumentException( 11086 "Unknown component: " + packageName 11087 + "/" + className); 11088 } 11089 // Allow root and verify that userId is not being specified by a different user 11090 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 11091 throw new SecurityException( 11092 "Permission Denial: attempt to change component state from pid=" 11093 + Binder.getCallingPid() 11094 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 11095 } 11096 if (className == null) { 11097 // We're dealing with an application/package level state change 11098 if (pkgSetting.getEnabled(userId) == newState) { 11099 // Nothing to do 11100 return; 11101 } 11102 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 11103 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 11104 // Don't care about who enables an app. 11105 callingPackage = null; 11106 } 11107 pkgSetting.setEnabled(newState, userId, callingPackage); 11108 // pkgSetting.pkg.mSetEnabled = newState; 11109 } else { 11110 // We're dealing with a component level state change 11111 // First, verify that this is a valid class name. 11112 PackageParser.Package pkg = pkgSetting.pkg; 11113 if (pkg == null || !pkg.hasComponentClassName(className)) { 11114 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 11115 throw new IllegalArgumentException("Component class " + className 11116 + " does not exist in " + packageName); 11117 } else { 11118 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 11119 + className + " does not exist in " + packageName); 11120 } 11121 } 11122 switch (newState) { 11123 case COMPONENT_ENABLED_STATE_ENABLED: 11124 if (!pkgSetting.enableComponentLPw(className, userId)) { 11125 return; 11126 } 11127 break; 11128 case COMPONENT_ENABLED_STATE_DISABLED: 11129 if (!pkgSetting.disableComponentLPw(className, userId)) { 11130 return; 11131 } 11132 break; 11133 case COMPONENT_ENABLED_STATE_DEFAULT: 11134 if (!pkgSetting.restoreComponentLPw(className, userId)) { 11135 return; 11136 } 11137 break; 11138 default: 11139 Slog.e(TAG, "Invalid new component state: " + newState); 11140 return; 11141 } 11142 } 11143 mSettings.writePackageRestrictionsLPr(userId); 11144 components = mPendingBroadcasts.get(userId, packageName); 11145 final boolean newPackage = components == null; 11146 if (newPackage) { 11147 components = new ArrayList<String>(); 11148 } 11149 if (!components.contains(componentName)) { 11150 components.add(componentName); 11151 } 11152 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 11153 sendNow = true; 11154 // Purge entry from pending broadcast list if another one exists already 11155 // since we are sending one right away. 11156 mPendingBroadcasts.remove(userId, packageName); 11157 } else { 11158 if (newPackage) { 11159 mPendingBroadcasts.put(userId, packageName, components); 11160 } 11161 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 11162 // Schedule a message 11163 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 11164 } 11165 } 11166 } 11167 11168 long callingId = Binder.clearCallingIdentity(); 11169 try { 11170 if (sendNow) { 11171 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 11172 sendPackageChangedBroadcast(packageName, 11173 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 11174 } 11175 } finally { 11176 Binder.restoreCallingIdentity(callingId); 11177 } 11178 } 11179 11180 private void sendPackageChangedBroadcast(String packageName, 11181 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 11182 if (DEBUG_INSTALL) 11183 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 11184 + componentNames); 11185 Bundle extras = new Bundle(4); 11186 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 11187 String nameList[] = new String[componentNames.size()]; 11188 componentNames.toArray(nameList); 11189 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 11190 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 11191 extras.putInt(Intent.EXTRA_UID, packageUid); 11192 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 11193 new int[] {UserHandle.getUserId(packageUid)}); 11194 } 11195 11196 @Override 11197 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 11198 if (!sUserManager.exists(userId)) return; 11199 final int uid = Binder.getCallingUid(); 11200 final int permission = mContext.checkCallingOrSelfPermission( 11201 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 11202 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 11203 enforceCrossUserPermission(uid, userId, true, "stop package"); 11204 // writer 11205 synchronized (mPackages) { 11206 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 11207 uid, userId)) { 11208 scheduleWritePackageRestrictionsLocked(userId); 11209 } 11210 } 11211 } 11212 11213 @Override 11214 public String getInstallerPackageName(String packageName) { 11215 // reader 11216 synchronized (mPackages) { 11217 return mSettings.getInstallerPackageNameLPr(packageName); 11218 } 11219 } 11220 11221 @Override 11222 public int getApplicationEnabledSetting(String packageName, int userId) { 11223 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11224 int uid = Binder.getCallingUid(); 11225 enforceCrossUserPermission(uid, userId, false, "get enabled"); 11226 // reader 11227 synchronized (mPackages) { 11228 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 11229 } 11230 } 11231 11232 @Override 11233 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 11234 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 11235 int uid = Binder.getCallingUid(); 11236 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 11237 // reader 11238 synchronized (mPackages) { 11239 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 11240 } 11241 } 11242 11243 @Override 11244 public void enterSafeMode() { 11245 enforceSystemOrRoot("Only the system can request entering safe mode"); 11246 11247 if (!mSystemReady) { 11248 mSafeMode = true; 11249 } 11250 } 11251 11252 @Override 11253 public void systemReady() { 11254 mSystemReady = true; 11255 11256 // Read the compatibilty setting when the system is ready. 11257 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 11258 mContext.getContentResolver(), 11259 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 11260 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 11261 if (DEBUG_SETTINGS) { 11262 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 11263 } 11264 11265 synchronized (mPackages) { 11266 // Verify that all of the preferred activity components actually 11267 // exist. It is possible for applications to be updated and at 11268 // that point remove a previously declared activity component that 11269 // had been set as a preferred activity. We try to clean this up 11270 // the next time we encounter that preferred activity, but it is 11271 // possible for the user flow to never be able to return to that 11272 // situation so here we do a sanity check to make sure we haven't 11273 // left any junk around. 11274 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 11275 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11276 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11277 removed.clear(); 11278 for (PreferredActivity pa : pir.filterSet()) { 11279 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 11280 removed.add(pa); 11281 } 11282 } 11283 if (removed.size() > 0) { 11284 for (int j=0; j<removed.size(); j++) { 11285 PreferredActivity pa = removed.get(i); 11286 Slog.w(TAG, "Removing dangling preferred activity: " 11287 + pa.mPref.mComponent); 11288 pir.removeFilter(pa); 11289 } 11290 mSettings.writePackageRestrictionsLPr( 11291 mSettings.mPreferredActivities.keyAt(i)); 11292 } 11293 } 11294 } 11295 sUserManager.systemReady(); 11296 } 11297 11298 @Override 11299 public boolean isSafeMode() { 11300 return mSafeMode; 11301 } 11302 11303 @Override 11304 public boolean hasSystemUidErrors() { 11305 return mHasSystemUidErrors; 11306 } 11307 11308 static String arrayToString(int[] array) { 11309 StringBuffer buf = new StringBuffer(128); 11310 buf.append('['); 11311 if (array != null) { 11312 for (int i=0; i<array.length; i++) { 11313 if (i > 0) buf.append(", "); 11314 buf.append(array[i]); 11315 } 11316 } 11317 buf.append(']'); 11318 return buf.toString(); 11319 } 11320 11321 static class DumpState { 11322 public static final int DUMP_LIBS = 1 << 0; 11323 11324 public static final int DUMP_FEATURES = 1 << 1; 11325 11326 public static final int DUMP_RESOLVERS = 1 << 2; 11327 11328 public static final int DUMP_PERMISSIONS = 1 << 3; 11329 11330 public static final int DUMP_PACKAGES = 1 << 4; 11331 11332 public static final int DUMP_SHARED_USERS = 1 << 5; 11333 11334 public static final int DUMP_MESSAGES = 1 << 6; 11335 11336 public static final int DUMP_PROVIDERS = 1 << 7; 11337 11338 public static final int DUMP_VERIFIERS = 1 << 8; 11339 11340 public static final int DUMP_PREFERRED = 1 << 9; 11341 11342 public static final int DUMP_PREFERRED_XML = 1 << 10; 11343 11344 public static final int DUMP_KEYSETS = 1 << 11; 11345 11346 public static final int OPTION_SHOW_FILTERS = 1 << 0; 11347 11348 private int mTypes; 11349 11350 private int mOptions; 11351 11352 private boolean mTitlePrinted; 11353 11354 private SharedUserSetting mSharedUser; 11355 11356 public boolean isDumping(int type) { 11357 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 11358 return true; 11359 } 11360 11361 return (mTypes & type) != 0; 11362 } 11363 11364 public void setDump(int type) { 11365 mTypes |= type; 11366 } 11367 11368 public boolean isOptionEnabled(int option) { 11369 return (mOptions & option) != 0; 11370 } 11371 11372 public void setOptionEnabled(int option) { 11373 mOptions |= option; 11374 } 11375 11376 public boolean onTitlePrinted() { 11377 final boolean printed = mTitlePrinted; 11378 mTitlePrinted = true; 11379 return printed; 11380 } 11381 11382 public boolean getTitlePrinted() { 11383 return mTitlePrinted; 11384 } 11385 11386 public void setTitlePrinted(boolean enabled) { 11387 mTitlePrinted = enabled; 11388 } 11389 11390 public SharedUserSetting getSharedUser() { 11391 return mSharedUser; 11392 } 11393 11394 public void setSharedUser(SharedUserSetting user) { 11395 mSharedUser = user; 11396 } 11397 } 11398 11399 @Override 11400 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 11401 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 11402 != PackageManager.PERMISSION_GRANTED) { 11403 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 11404 + Binder.getCallingPid() 11405 + ", uid=" + Binder.getCallingUid() 11406 + " without permission " 11407 + android.Manifest.permission.DUMP); 11408 return; 11409 } 11410 11411 DumpState dumpState = new DumpState(); 11412 boolean fullPreferred = false; 11413 boolean checkin = false; 11414 11415 String packageName = null; 11416 11417 int opti = 0; 11418 while (opti < args.length) { 11419 String opt = args[opti]; 11420 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 11421 break; 11422 } 11423 opti++; 11424 if ("-a".equals(opt)) { 11425 // Right now we only know how to print all. 11426 } else if ("-h".equals(opt)) { 11427 pw.println("Package manager dump options:"); 11428 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 11429 pw.println(" --checkin: dump for a checkin"); 11430 pw.println(" -f: print details of intent filters"); 11431 pw.println(" -h: print this help"); 11432 pw.println(" cmd may be one of:"); 11433 pw.println(" l[ibraries]: list known shared libraries"); 11434 pw.println(" f[ibraries]: list device features"); 11435 pw.println(" r[esolvers]: dump intent resolvers"); 11436 pw.println(" perm[issions]: dump permissions"); 11437 pw.println(" pref[erred]: print preferred package settings"); 11438 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 11439 pw.println(" prov[iders]: dump content providers"); 11440 pw.println(" p[ackages]: dump installed packages"); 11441 pw.println(" s[hared-users]: dump shared user IDs"); 11442 pw.println(" m[essages]: print collected runtime messages"); 11443 pw.println(" v[erifiers]: print package verifier info"); 11444 pw.println(" <package.name>: info about given package"); 11445 pw.println(" k[eysets]: print known keysets"); 11446 return; 11447 } else if ("--checkin".equals(opt)) { 11448 checkin = true; 11449 } else if ("-f".equals(opt)) { 11450 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11451 } else { 11452 pw.println("Unknown argument: " + opt + "; use -h for help"); 11453 } 11454 } 11455 11456 // Is the caller requesting to dump a particular piece of data? 11457 if (opti < args.length) { 11458 String cmd = args[opti]; 11459 opti++; 11460 // Is this a package name? 11461 if ("android".equals(cmd) || cmd.contains(".")) { 11462 packageName = cmd; 11463 // When dumping a single package, we always dump all of its 11464 // filter information since the amount of data will be reasonable. 11465 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 11466 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 11467 dumpState.setDump(DumpState.DUMP_LIBS); 11468 } else if ("f".equals(cmd) || "features".equals(cmd)) { 11469 dumpState.setDump(DumpState.DUMP_FEATURES); 11470 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 11471 dumpState.setDump(DumpState.DUMP_RESOLVERS); 11472 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 11473 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 11474 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 11475 dumpState.setDump(DumpState.DUMP_PREFERRED); 11476 } else if ("preferred-xml".equals(cmd)) { 11477 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 11478 if (opti < args.length && "--full".equals(args[opti])) { 11479 fullPreferred = true; 11480 opti++; 11481 } 11482 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 11483 dumpState.setDump(DumpState.DUMP_PACKAGES); 11484 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 11485 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 11486 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 11487 dumpState.setDump(DumpState.DUMP_PROVIDERS); 11488 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 11489 dumpState.setDump(DumpState.DUMP_MESSAGES); 11490 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 11491 dumpState.setDump(DumpState.DUMP_VERIFIERS); 11492 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 11493 dumpState.setDump(DumpState.DUMP_KEYSETS); 11494 } 11495 } 11496 11497 if (checkin) { 11498 pw.println("vers,1"); 11499 } 11500 11501 // reader 11502 synchronized (mPackages) { 11503 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 11504 if (!checkin) { 11505 if (dumpState.onTitlePrinted()) 11506 pw.println(); 11507 pw.println("Verifiers:"); 11508 pw.print(" Required: "); 11509 pw.print(mRequiredVerifierPackage); 11510 pw.print(" (uid="); 11511 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 11512 pw.println(")"); 11513 } else if (mRequiredVerifierPackage != null) { 11514 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 11515 pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0)); 11516 } 11517 } 11518 11519 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 11520 boolean printedHeader = false; 11521 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 11522 while (it.hasNext()) { 11523 String name = it.next(); 11524 SharedLibraryEntry ent = mSharedLibraries.get(name); 11525 if (!checkin) { 11526 if (!printedHeader) { 11527 if (dumpState.onTitlePrinted()) 11528 pw.println(); 11529 pw.println("Libraries:"); 11530 printedHeader = true; 11531 } 11532 pw.print(" "); 11533 } else { 11534 pw.print("lib,"); 11535 } 11536 pw.print(name); 11537 if (!checkin) { 11538 pw.print(" -> "); 11539 } 11540 if (ent.path != null) { 11541 if (!checkin) { 11542 pw.print("(jar) "); 11543 pw.print(ent.path); 11544 } else { 11545 pw.print(",jar,"); 11546 pw.print(ent.path); 11547 } 11548 } else { 11549 if (!checkin) { 11550 pw.print("(apk) "); 11551 pw.print(ent.apk); 11552 } else { 11553 pw.print(",apk,"); 11554 pw.print(ent.apk); 11555 } 11556 } 11557 pw.println(); 11558 } 11559 } 11560 11561 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 11562 if (dumpState.onTitlePrinted()) 11563 pw.println(); 11564 if (!checkin) { 11565 pw.println("Features:"); 11566 } 11567 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 11568 while (it.hasNext()) { 11569 String name = it.next(); 11570 if (!checkin) { 11571 pw.print(" "); 11572 } else { 11573 pw.print("feat,"); 11574 } 11575 pw.println(name); 11576 } 11577 } 11578 11579 if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 11580 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 11581 : "Activity Resolver Table:", " ", packageName, 11582 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11583 dumpState.setTitlePrinted(true); 11584 } 11585 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 11586 : "Receiver Resolver Table:", " ", packageName, 11587 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11588 dumpState.setTitlePrinted(true); 11589 } 11590 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 11591 : "Service Resolver Table:", " ", packageName, 11592 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11593 dumpState.setTitlePrinted(true); 11594 } 11595 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 11596 : "Provider Resolver Table:", " ", packageName, 11597 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 11598 dumpState.setTitlePrinted(true); 11599 } 11600 } 11601 11602 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 11603 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 11604 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 11605 int user = mSettings.mPreferredActivities.keyAt(i); 11606 if (pir.dump(pw, 11607 dumpState.getTitlePrinted() 11608 ? "\nPreferred Activities User " + user + ":" 11609 : "Preferred Activities User " + user + ":", " ", 11610 packageName, true)) { 11611 dumpState.setTitlePrinted(true); 11612 } 11613 } 11614 } 11615 11616 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 11617 pw.flush(); 11618 FileOutputStream fout = new FileOutputStream(fd); 11619 BufferedOutputStream str = new BufferedOutputStream(fout); 11620 XmlSerializer serializer = new FastXmlSerializer(); 11621 try { 11622 serializer.setOutput(str, "utf-8"); 11623 serializer.startDocument(null, true); 11624 serializer.setFeature( 11625 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 11626 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 11627 serializer.endDocument(); 11628 serializer.flush(); 11629 } catch (IllegalArgumentException e) { 11630 pw.println("Failed writing: " + e); 11631 } catch (IllegalStateException e) { 11632 pw.println("Failed writing: " + e); 11633 } catch (IOException e) { 11634 pw.println("Failed writing: " + e); 11635 } 11636 } 11637 11638 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 11639 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 11640 } 11641 11642 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 11643 boolean printedSomething = false; 11644 for (PackageParser.Provider p : mProviders.mProviders.values()) { 11645 if (packageName != null && !packageName.equals(p.info.packageName)) { 11646 continue; 11647 } 11648 if (!printedSomething) { 11649 if (dumpState.onTitlePrinted()) 11650 pw.println(); 11651 pw.println("Registered ContentProviders:"); 11652 printedSomething = true; 11653 } 11654 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 11655 pw.print(" "); pw.println(p.toString()); 11656 } 11657 printedSomething = false; 11658 for (Map.Entry<String, PackageParser.Provider> entry : 11659 mProvidersByAuthority.entrySet()) { 11660 PackageParser.Provider p = entry.getValue(); 11661 if (packageName != null && !packageName.equals(p.info.packageName)) { 11662 continue; 11663 } 11664 if (!printedSomething) { 11665 if (dumpState.onTitlePrinted()) 11666 pw.println(); 11667 pw.println("ContentProvider Authorities:"); 11668 printedSomething = true; 11669 } 11670 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 11671 pw.print(" "); pw.println(p.toString()); 11672 if (p.info != null && p.info.applicationInfo != null) { 11673 final String appInfo = p.info.applicationInfo.toString(); 11674 pw.print(" applicationInfo="); pw.println(appInfo); 11675 } 11676 } 11677 } 11678 11679 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 11680 mSettings.mKeySetManager.dump(pw, packageName, dumpState); 11681 } 11682 11683 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 11684 mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin); 11685 } 11686 11687 if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 11688 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 11689 } 11690 11691 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 11692 if (dumpState.onTitlePrinted()) 11693 pw.println(); 11694 mSettings.dumpReadMessagesLPr(pw, dumpState); 11695 11696 pw.println(); 11697 pw.println("Package warning messages:"); 11698 final File fname = getSettingsProblemFile(); 11699 FileInputStream in = null; 11700 try { 11701 in = new FileInputStream(fname); 11702 final int avail = in.available(); 11703 final byte[] data = new byte[avail]; 11704 in.read(data); 11705 pw.print(new String(data)); 11706 } catch (FileNotFoundException e) { 11707 } catch (IOException e) { 11708 } finally { 11709 if (in != null) { 11710 try { 11711 in.close(); 11712 } catch (IOException e) { 11713 } 11714 } 11715 } 11716 } 11717 } 11718 } 11719 11720 // ------- apps on sdcard specific code ------- 11721 static final boolean DEBUG_SD_INSTALL = false; 11722 11723 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 11724 11725 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 11726 11727 private boolean mMediaMounted = false; 11728 11729 private String getEncryptKey() { 11730 try { 11731 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 11732 SD_ENCRYPTION_KEYSTORE_NAME); 11733 if (sdEncKey == null) { 11734 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 11735 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 11736 if (sdEncKey == null) { 11737 Slog.e(TAG, "Failed to create encryption keys"); 11738 return null; 11739 } 11740 } 11741 return sdEncKey; 11742 } catch (NoSuchAlgorithmException nsae) { 11743 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 11744 return null; 11745 } catch (IOException ioe) { 11746 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 11747 return null; 11748 } 11749 11750 } 11751 11752 /* package */static String getTempContainerId() { 11753 int tmpIdx = 1; 11754 String list[] = PackageHelper.getSecureContainerList(); 11755 if (list != null) { 11756 for (final String name : list) { 11757 // Ignore null and non-temporary container entries 11758 if (name == null || !name.startsWith(mTempContainerPrefix)) { 11759 continue; 11760 } 11761 11762 String subStr = name.substring(mTempContainerPrefix.length()); 11763 try { 11764 int cid = Integer.parseInt(subStr); 11765 if (cid >= tmpIdx) { 11766 tmpIdx = cid + 1; 11767 } 11768 } catch (NumberFormatException e) { 11769 } 11770 } 11771 } 11772 return mTempContainerPrefix + tmpIdx; 11773 } 11774 11775 /* 11776 * Update media status on PackageManager. 11777 */ 11778 @Override 11779 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 11780 int callingUid = Binder.getCallingUid(); 11781 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 11782 throw new SecurityException("Media status can only be updated by the system"); 11783 } 11784 // reader; this apparently protects mMediaMounted, but should probably 11785 // be a different lock in that case. 11786 synchronized (mPackages) { 11787 Log.i(TAG, "Updating external media status from " 11788 + (mMediaMounted ? "mounted" : "unmounted") + " to " 11789 + (mediaStatus ? "mounted" : "unmounted")); 11790 if (DEBUG_SD_INSTALL) 11791 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 11792 + ", mMediaMounted=" + mMediaMounted); 11793 if (mediaStatus == mMediaMounted) { 11794 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 11795 : 0, -1); 11796 mHandler.sendMessage(msg); 11797 return; 11798 } 11799 mMediaMounted = mediaStatus; 11800 } 11801 // Queue up an async operation since the package installation may take a 11802 // little while. 11803 mHandler.post(new Runnable() { 11804 public void run() { 11805 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 11806 } 11807 }); 11808 } 11809 11810 /** 11811 * Called by MountService when the initial ASECs to scan are available. 11812 * Should block until all the ASEC containers are finished being scanned. 11813 */ 11814 public void scanAvailableAsecs() { 11815 updateExternalMediaStatusInner(true, false, false); 11816 if (mShouldRestoreconData) { 11817 SELinuxMMAC.setRestoreconDone(); 11818 mShouldRestoreconData = false; 11819 } 11820 } 11821 11822 /* 11823 * Collect information of applications on external media, map them against 11824 * existing containers and update information based on current mount status. 11825 * Please note that we always have to report status if reportStatus has been 11826 * set to true especially when unloading packages. 11827 */ 11828 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 11829 boolean externalStorage) { 11830 // Collection of uids 11831 int uidArr[] = null; 11832 // Collection of stale containers 11833 HashSet<String> removeCids = new HashSet<String>(); 11834 // Collection of packages on external media with valid containers. 11835 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 11836 // Get list of secure containers. 11837 final String list[] = PackageHelper.getSecureContainerList(); 11838 if (list == null || list.length == 0) { 11839 Log.i(TAG, "No secure containers on sdcard"); 11840 } else { 11841 // Process list of secure containers and categorize them 11842 // as active or stale based on their package internal state. 11843 int uidList[] = new int[list.length]; 11844 int num = 0; 11845 // reader 11846 synchronized (mPackages) { 11847 for (String cid : list) { 11848 if (DEBUG_SD_INSTALL) 11849 Log.i(TAG, "Processing container " + cid); 11850 String pkgName = getAsecPackageName(cid); 11851 if (pkgName == null) { 11852 if (DEBUG_SD_INSTALL) 11853 Log.i(TAG, "Container : " + cid + " stale"); 11854 removeCids.add(cid); 11855 continue; 11856 } 11857 if (DEBUG_SD_INSTALL) 11858 Log.i(TAG, "Looking for pkg : " + pkgName); 11859 11860 final PackageSetting ps = mSettings.mPackages.get(pkgName); 11861 if (ps == null) { 11862 Log.i(TAG, "Deleting container with no matching settings " + cid); 11863 removeCids.add(cid); 11864 continue; 11865 } 11866 11867 /* 11868 * Skip packages that are not external if we're unmounting 11869 * external storage. 11870 */ 11871 if (externalStorage && !isMounted && !isExternal(ps)) { 11872 continue; 11873 } 11874 11875 final AsecInstallArgs args = new AsecInstallArgs(cid, 11876 getAppInstructionSetFromSettings(ps), 11877 isForwardLocked(ps)); 11878 // The package status is changed only if the code path 11879 // matches between settings and the container id. 11880 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 11881 if (DEBUG_SD_INSTALL) { 11882 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 11883 + " at code path: " + ps.codePathString); 11884 } 11885 11886 // We do have a valid package installed on sdcard 11887 processCids.put(args, ps.codePathString); 11888 final int uid = ps.appId; 11889 if (uid != -1) { 11890 uidList[num++] = uid; 11891 } 11892 } else { 11893 Log.i(TAG, "Deleting stale container for " + cid); 11894 removeCids.add(cid); 11895 } 11896 } 11897 } 11898 11899 if (num > 0) { 11900 // Sort uid list 11901 Arrays.sort(uidList, 0, num); 11902 // Throw away duplicates 11903 uidArr = new int[num]; 11904 uidArr[0] = uidList[0]; 11905 int di = 0; 11906 for (int i = 1; i < num; i++) { 11907 if (uidList[i - 1] != uidList[i]) { 11908 uidArr[di++] = uidList[i]; 11909 } 11910 } 11911 } 11912 } 11913 // Process packages with valid entries. 11914 if (isMounted) { 11915 if (DEBUG_SD_INSTALL) 11916 Log.i(TAG, "Loading packages"); 11917 loadMediaPackages(processCids, uidArr, removeCids); 11918 startCleaningPackages(); 11919 } else { 11920 if (DEBUG_SD_INSTALL) 11921 Log.i(TAG, "Unloading packages"); 11922 unloadMediaPackages(processCids, uidArr, reportStatus); 11923 } 11924 } 11925 11926 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 11927 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 11928 int size = pkgList.size(); 11929 if (size > 0) { 11930 // Send broadcasts here 11931 Bundle extras = new Bundle(); 11932 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 11933 .toArray(new String[size])); 11934 if (uidArr != null) { 11935 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 11936 } 11937 if (replacing) { 11938 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 11939 } 11940 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 11941 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 11942 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 11943 } 11944 } 11945 11946 /* 11947 * Look at potentially valid container ids from processCids If package 11948 * information doesn't match the one on record or package scanning fails, 11949 * the cid is added to list of removeCids. We currently don't delete stale 11950 * containers. 11951 */ 11952 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 11953 HashSet<String> removeCids) { 11954 ArrayList<String> pkgList = new ArrayList<String>(); 11955 Set<AsecInstallArgs> keys = processCids.keySet(); 11956 boolean doGc = false; 11957 for (AsecInstallArgs args : keys) { 11958 String codePath = processCids.get(args); 11959 if (DEBUG_SD_INSTALL) 11960 Log.i(TAG, "Loading container : " + args.cid); 11961 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 11962 try { 11963 // Make sure there are no container errors first. 11964 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 11965 Slog.e(TAG, "Failed to mount cid : " + args.cid 11966 + " when installing from sdcard"); 11967 continue; 11968 } 11969 // Check code path here. 11970 if (codePath == null || !codePath.equals(args.getCodePath())) { 11971 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 11972 + " does not match one in settings " + codePath); 11973 continue; 11974 } 11975 // Parse package 11976 int parseFlags = mDefParseFlags; 11977 if (args.isExternal()) { 11978 parseFlags |= PackageParser.PARSE_ON_SDCARD; 11979 } 11980 if (args.isFwdLocked()) { 11981 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 11982 } 11983 11984 doGc = true; 11985 synchronized (mInstallLock) { 11986 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 11987 0, 0, null, null); 11988 // Scan the package 11989 if (pkg != null) { 11990 /* 11991 * TODO why is the lock being held? doPostInstall is 11992 * called in other places without the lock. This needs 11993 * to be straightened out. 11994 */ 11995 // writer 11996 synchronized (mPackages) { 11997 retCode = PackageManager.INSTALL_SUCCEEDED; 11998 pkgList.add(pkg.packageName); 11999 // Post process args 12000 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 12001 pkg.applicationInfo.uid); 12002 } 12003 } else { 12004 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 12005 } 12006 } 12007 12008 } finally { 12009 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 12010 // Don't destroy container here. Wait till gc clears things 12011 // up. 12012 removeCids.add(args.cid); 12013 } 12014 } 12015 } 12016 // writer 12017 synchronized (mPackages) { 12018 // If the platform SDK has changed since the last time we booted, 12019 // we need to re-grant app permission to catch any new ones that 12020 // appear. This is really a hack, and means that apps can in some 12021 // cases get permissions that the user didn't initially explicitly 12022 // allow... it would be nice to have some better way to handle 12023 // this situation. 12024 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 12025 if (regrantPermissions) 12026 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 12027 + mSdkVersion + "; regranting permissions for external storage"); 12028 mSettings.mExternalSdkPlatform = mSdkVersion; 12029 12030 // Make sure group IDs have been assigned, and any permission 12031 // changes in other apps are accounted for 12032 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 12033 | (regrantPermissions 12034 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 12035 : 0)); 12036 // can downgrade to reader 12037 // Persist settings 12038 mSettings.writeLPr(); 12039 } 12040 // Send a broadcast to let everyone know we are done processing 12041 if (pkgList.size() > 0) { 12042 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12043 } 12044 // Force gc to avoid any stale parser references that we might have. 12045 if (doGc) { 12046 Runtime.getRuntime().gc(); 12047 } 12048 // List stale containers and destroy stale temporary containers. 12049 if (removeCids != null) { 12050 for (String cid : removeCids) { 12051 if (cid.startsWith(mTempContainerPrefix)) { 12052 Log.i(TAG, "Destroying stale temporary container " + cid); 12053 PackageHelper.destroySdDir(cid); 12054 } else { 12055 Log.w(TAG, "Container " + cid + " is stale"); 12056 } 12057 } 12058 } 12059 } 12060 12061 /* 12062 * Utility method to unload a list of specified containers 12063 */ 12064 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 12065 // Just unmount all valid containers. 12066 for (AsecInstallArgs arg : cidArgs) { 12067 synchronized (mInstallLock) { 12068 arg.doPostDeleteLI(false); 12069 } 12070 } 12071 } 12072 12073 /* 12074 * Unload packages mounted on external media. This involves deleting package 12075 * data from internal structures, sending broadcasts about diabled packages, 12076 * gc'ing to free up references, unmounting all secure containers 12077 * corresponding to packages on external media, and posting a 12078 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 12079 * that we always have to post this message if status has been requested no 12080 * matter what. 12081 */ 12082 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 12083 final boolean reportStatus) { 12084 if (DEBUG_SD_INSTALL) 12085 Log.i(TAG, "unloading media packages"); 12086 ArrayList<String> pkgList = new ArrayList<String>(); 12087 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 12088 final Set<AsecInstallArgs> keys = processCids.keySet(); 12089 for (AsecInstallArgs args : keys) { 12090 String pkgName = args.getPackageName(); 12091 if (DEBUG_SD_INSTALL) 12092 Log.i(TAG, "Trying to unload pkg : " + pkgName); 12093 // Delete package internally 12094 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 12095 synchronized (mInstallLock) { 12096 boolean res = deletePackageLI(pkgName, null, false, null, null, 12097 PackageManager.DELETE_KEEP_DATA, outInfo, false); 12098 if (res) { 12099 pkgList.add(pkgName); 12100 } else { 12101 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 12102 failedList.add(args); 12103 } 12104 } 12105 } 12106 12107 // reader 12108 synchronized (mPackages) { 12109 // We didn't update the settings after removing each package; 12110 // write them now for all packages. 12111 mSettings.writeLPr(); 12112 } 12113 12114 // We have to absolutely send UPDATED_MEDIA_STATUS only 12115 // after confirming that all the receivers processed the ordered 12116 // broadcast when packages get disabled, force a gc to clean things up. 12117 // and unload all the containers. 12118 if (pkgList.size() > 0) { 12119 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 12120 new IIntentReceiver.Stub() { 12121 public void performReceive(Intent intent, int resultCode, String data, 12122 Bundle extras, boolean ordered, boolean sticky, 12123 int sendingUser) throws RemoteException { 12124 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 12125 reportStatus ? 1 : 0, 1, keys); 12126 mHandler.sendMessage(msg); 12127 } 12128 }); 12129 } else { 12130 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 12131 keys); 12132 mHandler.sendMessage(msg); 12133 } 12134 } 12135 12136 /** Binder call */ 12137 @Override 12138 public void movePackage(final String packageName, final IPackageMoveObserver observer, 12139 final int flags) { 12140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 12141 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 12142 int returnCode = PackageManager.MOVE_SUCCEEDED; 12143 int currFlags = 0; 12144 int newFlags = 0; 12145 // reader 12146 synchronized (mPackages) { 12147 PackageParser.Package pkg = mPackages.get(packageName); 12148 if (pkg == null) { 12149 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12150 } else { 12151 // Disable moving fwd locked apps and system packages 12152 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 12153 Slog.w(TAG, "Cannot move system application"); 12154 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 12155 } else if (pkg.mOperationPending) { 12156 Slog.w(TAG, "Attempt to move package which has pending operations"); 12157 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 12158 } else { 12159 // Find install location first 12160 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 12161 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 12162 Slog.w(TAG, "Ambigous flags specified for move location."); 12163 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12164 } else { 12165 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 12166 : PackageManager.INSTALL_INTERNAL; 12167 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 12168 : PackageManager.INSTALL_INTERNAL; 12169 12170 if (newFlags == currFlags) { 12171 Slog.w(TAG, "No move required. Trying to move to same location"); 12172 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 12173 } else { 12174 if (isForwardLocked(pkg)) { 12175 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12176 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 12177 } 12178 } 12179 } 12180 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12181 pkg.mOperationPending = true; 12182 } 12183 } 12184 } 12185 12186 /* 12187 * TODO this next block probably shouldn't be inside the lock. We 12188 * can't guarantee these won't change after this is fired off 12189 * anyway. 12190 */ 12191 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12192 processPendingMove(new MoveParams(null, observer, 0, packageName, null, 12193 null, -1, user), 12194 returnCode); 12195 } else { 12196 Message msg = mHandler.obtainMessage(INIT_COPY); 12197 final String instructionSet = getAppInstructionSet(pkg.applicationInfo); 12198 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 12199 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir, 12200 instructionSet); 12201 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 12202 pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user); 12203 msg.obj = mp; 12204 mHandler.sendMessage(msg); 12205 } 12206 } 12207 } 12208 12209 private void processPendingMove(final MoveParams mp, final int currentStatus) { 12210 // Queue up an async operation since the package deletion may take a 12211 // little while. 12212 mHandler.post(new Runnable() { 12213 public void run() { 12214 // TODO fix this; this does nothing. 12215 mHandler.removeCallbacks(this); 12216 int returnCode = currentStatus; 12217 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 12218 int uidArr[] = null; 12219 ArrayList<String> pkgList = null; 12220 synchronized (mPackages) { 12221 PackageParser.Package pkg = mPackages.get(mp.packageName); 12222 if (pkg == null) { 12223 Slog.w(TAG, " Package " + mp.packageName 12224 + " doesn't exist. Aborting move"); 12225 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12226 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 12227 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 12228 + mp.srcArgs.getCodePath() + " to " 12229 + pkg.applicationInfo.sourceDir 12230 + " Aborting move and returning error"); 12231 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12232 } else { 12233 uidArr = new int[] { 12234 pkg.applicationInfo.uid 12235 }; 12236 pkgList = new ArrayList<String>(); 12237 pkgList.add(mp.packageName); 12238 } 12239 } 12240 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12241 // Send resources unavailable broadcast 12242 sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null); 12243 // Update package code and resource paths 12244 synchronized (mInstallLock) { 12245 synchronized (mPackages) { 12246 PackageParser.Package pkg = mPackages.get(mp.packageName); 12247 // Recheck for package again. 12248 if (pkg == null) { 12249 Slog.w(TAG, " Package " + mp.packageName 12250 + " doesn't exist. Aborting move"); 12251 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 12252 } else if (!mp.srcArgs.getCodePath().equals( 12253 pkg.applicationInfo.sourceDir)) { 12254 Slog.w(TAG, "Package " + mp.packageName 12255 + " code path changed from " + mp.srcArgs.getCodePath() 12256 + " to " + pkg.applicationInfo.sourceDir 12257 + " Aborting move and returning error"); 12258 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12259 } else { 12260 final String oldCodePath = pkg.mPath; 12261 final String newCodePath = mp.targetArgs.getCodePath(); 12262 final String newResPath = mp.targetArgs.getResourcePath(); 12263 final String newNativePath = mp.targetArgs 12264 .getNativeLibraryPath(); 12265 12266 final File newNativeDir = new File(newNativePath); 12267 12268 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 12269 ApkHandle handle = null; 12270 try { 12271 handle = ApkHandle.create(newCodePath); 12272 final int abi = NativeLibraryHelper.findSupportedAbi( 12273 handle, Build.SUPPORTED_ABIS); 12274 if (abi >= 0) { 12275 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 12276 handle, newNativeDir, Build.SUPPORTED_ABIS[abi]); 12277 } 12278 } catch (IOException ioe) { 12279 Slog.w(TAG, "Unable to extract native libs for package :" 12280 + mp.packageName, ioe); 12281 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 12282 } finally { 12283 IoUtils.closeQuietly(handle); 12284 } 12285 } 12286 final int[] users = sUserManager.getUserIds(); 12287 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12288 for (int user : users) { 12289 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 12290 newNativePath, user) < 0) { 12291 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12292 } 12293 } 12294 } 12295 12296 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12297 pkg.mPath = newCodePath; 12298 // Move dex files around 12299 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 12300 // Moving of dex files failed. Set 12301 // error code and abort move. 12302 pkg.mPath = pkg.mScanPath; 12303 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 12304 } 12305 } 12306 12307 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 12308 pkg.mScanPath = newCodePath; 12309 pkg.applicationInfo.sourceDir = newCodePath; 12310 pkg.applicationInfo.publicSourceDir = newResPath; 12311 pkg.applicationInfo.nativeLibraryDir = newNativePath; 12312 PackageSetting ps = (PackageSetting) pkg.mExtras; 12313 ps.codePath = new File(pkg.applicationInfo.sourceDir); 12314 ps.codePathString = ps.codePath.getPath(); 12315 ps.resourcePath = new File( 12316 pkg.applicationInfo.publicSourceDir); 12317 ps.resourcePathString = ps.resourcePath.getPath(); 12318 ps.nativeLibraryPathString = newNativePath; 12319 // Set the application info flag 12320 // correctly. 12321 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 12322 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12323 } else { 12324 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 12325 } 12326 ps.setFlags(pkg.applicationInfo.flags); 12327 mAppDirs.remove(oldCodePath); 12328 mAppDirs.put(newCodePath, pkg); 12329 // Persist settings 12330 mSettings.writeLPr(); 12331 } 12332 } 12333 } 12334 } 12335 // Send resources available broadcast 12336 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 12337 } 12338 } 12339 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 12340 // Clean up failed installation 12341 if (mp.targetArgs != null) { 12342 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 12343 -1); 12344 } 12345 } else { 12346 // Force a gc to clear things up. 12347 Runtime.getRuntime().gc(); 12348 // Delete older code 12349 synchronized (mInstallLock) { 12350 mp.srcArgs.doPostDeleteLI(true); 12351 } 12352 } 12353 12354 // Allow more operations on this file if we didn't fail because 12355 // an operation was already pending for this package. 12356 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 12357 synchronized (mPackages) { 12358 PackageParser.Package pkg = mPackages.get(mp.packageName); 12359 if (pkg != null) { 12360 pkg.mOperationPending = false; 12361 } 12362 } 12363 } 12364 12365 IPackageMoveObserver observer = mp.observer; 12366 if (observer != null) { 12367 try { 12368 observer.packageMoved(mp.packageName, returnCode); 12369 } catch (RemoteException e) { 12370 Log.i(TAG, "Observer no longer exists."); 12371 } 12372 } 12373 } 12374 }); 12375 } 12376 12377 @Override 12378 public boolean setInstallLocation(int loc) { 12379 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 12380 null); 12381 if (getInstallLocation() == loc) { 12382 return true; 12383 } 12384 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 12385 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 12386 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 12387 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 12388 return true; 12389 } 12390 return false; 12391 } 12392 12393 @Override 12394 public int getInstallLocation() { 12395 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12396 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 12397 PackageHelper.APP_INSTALL_AUTO); 12398 } 12399 12400 /** Called by UserManagerService */ 12401 void cleanUpUserLILPw(int userHandle) { 12402 mDirtyUsers.remove(userHandle); 12403 mSettings.removeUserLPr(userHandle); 12404 mPendingBroadcasts.remove(userHandle); 12405 if (mInstaller != null) { 12406 // Technically, we shouldn't be doing this with the package lock 12407 // held. However, this is very rare, and there is already so much 12408 // other disk I/O going on, that we'll let it slide for now. 12409 mInstaller.removeUserDataDirs(userHandle); 12410 } 12411 } 12412 12413 /** Called by UserManagerService */ 12414 void createNewUserLILPw(int userHandle, File path) { 12415 if (mInstaller != null) { 12416 mInstaller.createUserConfig(userHandle); 12417 mSettings.createNewUserLILPw(this, mInstaller, userHandle, path); 12418 } 12419 } 12420 12421 @Override 12422 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 12423 mContext.enforceCallingOrSelfPermission( 12424 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12425 "Only package verification agents can read the verifier device identity"); 12426 12427 synchronized (mPackages) { 12428 return mSettings.getVerifierDeviceIdentityLPw(); 12429 } 12430 } 12431 12432 @Override 12433 public void setPermissionEnforced(String permission, boolean enforced) { 12434 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 12435 if (READ_EXTERNAL_STORAGE.equals(permission)) { 12436 synchronized (mPackages) { 12437 if (mSettings.mReadExternalStorageEnforced == null 12438 || mSettings.mReadExternalStorageEnforced != enforced) { 12439 mSettings.mReadExternalStorageEnforced = enforced; 12440 mSettings.writeLPr(); 12441 } 12442 } 12443 // kill any non-foreground processes so we restart them and 12444 // grant/revoke the GID. 12445 final IActivityManager am = ActivityManagerNative.getDefault(); 12446 if (am != null) { 12447 final long token = Binder.clearCallingIdentity(); 12448 try { 12449 am.killProcessesBelowForeground("setPermissionEnforcement"); 12450 } catch (RemoteException e) { 12451 } finally { 12452 Binder.restoreCallingIdentity(token); 12453 } 12454 } 12455 } else { 12456 throw new IllegalArgumentException("No selective enforcement for " + permission); 12457 } 12458 } 12459 12460 @Override 12461 @Deprecated 12462 public boolean isPermissionEnforced(String permission) { 12463 return true; 12464 } 12465 12466 @Override 12467 public boolean isStorageLow() { 12468 final long token = Binder.clearCallingIdentity(); 12469 try { 12470 final DeviceStorageMonitorInternal 12471 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 12472 if (dsm != null) { 12473 return dsm.isMemoryLow(); 12474 } else { 12475 return false; 12476 } 12477 } finally { 12478 Binder.restoreCallingIdentity(token); 12479 } 12480 } 12481} 12482