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