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