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