PackageManagerService.java revision 7de350a91301985b7f2d9f28edde5aade8495d9b
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(scannedPkg, 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; 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 int ret = mInstaller.linkNativeLibraryDirectory(dataPathString, 4114 pkg.applicationInfo.nativeLibraryDir); 4115 if (ret < 0) { 4116 Slog.w(TAG, "Failed linking native library dir for " + path); 4117 mLastScanError = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 4118 return null; 4119 } 4120 } 4121 } catch (IOException ioe) { 4122 Log.e(TAG, "Unable to get canonical file " + ioe.toString()); 4123 } 4124 } 4125 pkg.mScanPath = path; 4126 4127 if ((scanMode&SCAN_NO_DEX) == 0) { 4128 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0) 4129 == DEX_OPT_FAILED) { 4130 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 4131 return null; 4132 } 4133 } 4134 4135 if (mFactoryTest && pkg.requestedPermissions.contains( 4136 android.Manifest.permission.FACTORY_TEST)) { 4137 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 4138 } 4139 4140 // Request the ActivityManager to kill the process(only for existing packages) 4141 // so that we do not end up in a confused state while the user is still using the older 4142 // version of the application while the new one gets installed. 4143 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 4144 killApplication(pkg.applicationInfo.packageName, 4145 pkg.applicationInfo.uid); 4146 } 4147 4148 // writer 4149 synchronized (mPackages) { 4150 // We don't expect installation to fail beyond this point, 4151 if ((scanMode&SCAN_MONITOR) != 0) { 4152 mAppDirs.put(pkg.mPath, pkg); 4153 } 4154 // Add the new setting to mSettings 4155 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 4156 // Add the new setting to mPackages 4157 mPackages.put(pkg.applicationInfo.packageName, pkg); 4158 // Make sure we don't accidentally delete its data. 4159 for (int i=0; i<mSettings.mPackagesToBeCleaned.size(); i++) { 4160 mSettings.mPackagesToBeCleaned.valueAt(i).remove(pkgName); 4161 } 4162 4163 // Take care of first install / last update times. 4164 if (currentTime != 0) { 4165 if (pkgSetting.firstInstallTime == 0) { 4166 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 4167 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 4168 pkgSetting.lastUpdateTime = currentTime; 4169 } 4170 } else if (pkgSetting.firstInstallTime == 0) { 4171 // We need *something*. Take time time stamp of the file. 4172 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 4173 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 4174 if (scanFileTime != pkgSetting.timeStamp) { 4175 // A package on the system image has changed; consider this 4176 // to be an update. 4177 pkgSetting.lastUpdateTime = scanFileTime; 4178 } 4179 } 4180 4181 int N = pkg.providers.size(); 4182 StringBuilder r = null; 4183 int i; 4184 for (i=0; i<N; i++) { 4185 PackageParser.Provider p = pkg.providers.get(i); 4186 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 4187 p.info.processName, pkg.applicationInfo.uid); 4188 mProvidersByComponent.put(new ComponentName(p.info.packageName, 4189 p.info.name), p); 4190 p.syncable = p.info.isSyncable; 4191 if (p.info.authority != null) { 4192 String names[] = p.info.authority.split(";"); 4193 p.info.authority = null; 4194 for (int j = 0; j < names.length; j++) { 4195 if (j == 1 && p.syncable) { 4196 // We only want the first authority for a provider to possibly be 4197 // syncable, so if we already added this provider using a different 4198 // authority clear the syncable flag. We copy the provider before 4199 // changing it because the mProviders object contains a reference 4200 // to a provider that we don't want to change. 4201 // Only do this for the second authority since the resulting provider 4202 // object can be the same for all future authorities for this provider. 4203 p = new PackageParser.Provider(p); 4204 p.syncable = false; 4205 } 4206 if (!mProviders.containsKey(names[j])) { 4207 mProviders.put(names[j], p); 4208 if (p.info.authority == null) { 4209 p.info.authority = names[j]; 4210 } else { 4211 p.info.authority = p.info.authority + ";" + names[j]; 4212 } 4213 if (DEBUG_PACKAGE_SCANNING) { 4214 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4215 Log.d(TAG, "Registered content provider: " + names[j] 4216 + ", className = " + p.info.name + ", isSyncable = " 4217 + p.info.isSyncable); 4218 } 4219 } else { 4220 PackageParser.Provider other = mProviders.get(names[j]); 4221 Slog.w(TAG, "Skipping provider name " + names[j] + 4222 " (in package " + pkg.applicationInfo.packageName + 4223 "): name already used by " 4224 + ((other != null && other.getComponentName() != null) 4225 ? other.getComponentName().getPackageName() : "?")); 4226 } 4227 } 4228 } 4229 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4230 if (r == null) { 4231 r = new StringBuilder(256); 4232 } else { 4233 r.append(' '); 4234 } 4235 r.append(p.info.name); 4236 } 4237 } 4238 if (r != null) { 4239 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 4240 } 4241 4242 N = pkg.services.size(); 4243 r = null; 4244 for (i=0; i<N; i++) { 4245 PackageParser.Service s = pkg.services.get(i); 4246 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 4247 s.info.processName, pkg.applicationInfo.uid); 4248 mServices.addService(s); 4249 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4250 if (r == null) { 4251 r = new StringBuilder(256); 4252 } else { 4253 r.append(' '); 4254 } 4255 r.append(s.info.name); 4256 } 4257 } 4258 if (r != null) { 4259 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 4260 } 4261 4262 N = pkg.receivers.size(); 4263 r = null; 4264 for (i=0; i<N; i++) { 4265 PackageParser.Activity a = pkg.receivers.get(i); 4266 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4267 a.info.processName, pkg.applicationInfo.uid); 4268 mReceivers.addActivity(a, "receiver"); 4269 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4270 if (r == null) { 4271 r = new StringBuilder(256); 4272 } else { 4273 r.append(' '); 4274 } 4275 r.append(a.info.name); 4276 } 4277 } 4278 if (r != null) { 4279 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 4280 } 4281 4282 N = pkg.activities.size(); 4283 r = null; 4284 for (i=0; i<N; i++) { 4285 PackageParser.Activity a = pkg.activities.get(i); 4286 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4287 a.info.processName, pkg.applicationInfo.uid); 4288 mActivities.addActivity(a, "activity"); 4289 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4290 if (r == null) { 4291 r = new StringBuilder(256); 4292 } else { 4293 r.append(' '); 4294 } 4295 r.append(a.info.name); 4296 } 4297 } 4298 if (r != null) { 4299 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 4300 } 4301 4302 N = pkg.permissionGroups.size(); 4303 r = null; 4304 for (i=0; i<N; i++) { 4305 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 4306 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 4307 if (cur == null) { 4308 mPermissionGroups.put(pg.info.name, pg); 4309 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4310 if (r == null) { 4311 r = new StringBuilder(256); 4312 } else { 4313 r.append(' '); 4314 } 4315 r.append(pg.info.name); 4316 } 4317 } else { 4318 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 4319 + pg.info.packageName + " ignored: original from " 4320 + cur.info.packageName); 4321 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4322 if (r == null) { 4323 r = new StringBuilder(256); 4324 } else { 4325 r.append(' '); 4326 } 4327 r.append("DUP:"); 4328 r.append(pg.info.name); 4329 } 4330 } 4331 } 4332 if (r != null) { 4333 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 4334 } 4335 4336 N = pkg.permissions.size(); 4337 r = null; 4338 for (i=0; i<N; i++) { 4339 PackageParser.Permission p = pkg.permissions.get(i); 4340 HashMap<String, BasePermission> permissionMap = 4341 p.tree ? mSettings.mPermissionTrees 4342 : mSettings.mPermissions; 4343 p.group = mPermissionGroups.get(p.info.group); 4344 if (p.info.group == null || p.group != null) { 4345 BasePermission bp = permissionMap.get(p.info.name); 4346 if (bp == null) { 4347 bp = new BasePermission(p.info.name, p.info.packageName, 4348 BasePermission.TYPE_NORMAL); 4349 permissionMap.put(p.info.name, bp); 4350 } 4351 if (bp.perm == null) { 4352 if (bp.sourcePackage == null 4353 || bp.sourcePackage.equals(p.info.packageName)) { 4354 BasePermission tree = findPermissionTreeLP(p.info.name); 4355 if (tree == null 4356 || tree.sourcePackage.equals(p.info.packageName)) { 4357 bp.packageSetting = pkgSetting; 4358 bp.perm = p; 4359 bp.uid = pkg.applicationInfo.uid; 4360 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4361 if (r == null) { 4362 r = new StringBuilder(256); 4363 } else { 4364 r.append(' '); 4365 } 4366 r.append(p.info.name); 4367 } 4368 } else { 4369 Slog.w(TAG, "Permission " + p.info.name + " from package " 4370 + p.info.packageName + " ignored: base tree " 4371 + tree.name + " is from package " 4372 + tree.sourcePackage); 4373 } 4374 } else { 4375 Slog.w(TAG, "Permission " + p.info.name + " from package " 4376 + p.info.packageName + " ignored: original from " 4377 + bp.sourcePackage); 4378 } 4379 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4380 if (r == null) { 4381 r = new StringBuilder(256); 4382 } else { 4383 r.append(' '); 4384 } 4385 r.append("DUP:"); 4386 r.append(p.info.name); 4387 } 4388 if (bp.perm == p) { 4389 bp.protectionLevel = p.info.protectionLevel; 4390 } 4391 } else { 4392 Slog.w(TAG, "Permission " + p.info.name + " from package " 4393 + p.info.packageName + " ignored: no group " 4394 + p.group); 4395 } 4396 } 4397 if (r != null) { 4398 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 4399 } 4400 4401 N = pkg.instrumentation.size(); 4402 r = null; 4403 for (i=0; i<N; i++) { 4404 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 4405 a.info.packageName = pkg.applicationInfo.packageName; 4406 a.info.sourceDir = pkg.applicationInfo.sourceDir; 4407 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 4408 a.info.dataDir = pkg.applicationInfo.dataDir; 4409 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 4410 mInstrumentation.put(a.getComponentName(), a); 4411 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4412 if (r == null) { 4413 r = new StringBuilder(256); 4414 } else { 4415 r.append(' '); 4416 } 4417 r.append(a.info.name); 4418 } 4419 } 4420 if (r != null) { 4421 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 4422 } 4423 4424 if (pkg.protectedBroadcasts != null) { 4425 N = pkg.protectedBroadcasts.size(); 4426 for (i=0; i<N; i++) { 4427 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 4428 } 4429 } 4430 4431 pkgSetting.setTimeStamp(scanFileTime); 4432 } 4433 4434 return pkg; 4435 } 4436 4437 private void killApplication(String pkgName, int uid) { 4438 // Request the ActivityManager to kill the process(only for existing packages) 4439 // so that we do not end up in a confused state while the user is still using the older 4440 // version of the application while the new one gets installed. 4441 IActivityManager am = ActivityManagerNative.getDefault(); 4442 if (am != null) { 4443 try { 4444 am.killApplicationWithUid(pkgName, uid); 4445 } catch (RemoteException e) { 4446 } 4447 } 4448 } 4449 4450 void removePackageLI(PackageParser.Package pkg, boolean chatty) { 4451 if (DEBUG_INSTALL) { 4452 if (chatty) 4453 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 4454 } 4455 4456 // writer 4457 synchronized (mPackages) { 4458 mPackages.remove(pkg.applicationInfo.packageName); 4459 if (pkg.mPath != null) { 4460 mAppDirs.remove(pkg.mPath); 4461 } 4462 4463 int N = pkg.providers.size(); 4464 StringBuilder r = null; 4465 int i; 4466 for (i=0; i<N; i++) { 4467 PackageParser.Provider p = pkg.providers.get(i); 4468 mProvidersByComponent.remove(new ComponentName(p.info.packageName, 4469 p.info.name)); 4470 if (p.info.authority == null) { 4471 4472 /* The is another ContentProvider with this authority when 4473 * this app was installed so this authority is null, 4474 * Ignore it as we don't have to unregister the provider. 4475 */ 4476 continue; 4477 } 4478 String names[] = p.info.authority.split(";"); 4479 for (int j = 0; j < names.length; j++) { 4480 if (mProviders.get(names[j]) == p) { 4481 mProviders.remove(names[j]); 4482 if (DEBUG_REMOVE) { 4483 if (chatty) 4484 Log.d(TAG, "Unregistered content provider: " + names[j] 4485 + ", className = " + p.info.name + ", isSyncable = " 4486 + p.info.isSyncable); 4487 } 4488 } 4489 } 4490 if (chatty) { 4491 if (r == null) { 4492 r = new StringBuilder(256); 4493 } else { 4494 r.append(' '); 4495 } 4496 r.append(p.info.name); 4497 } 4498 } 4499 if (r != null) { 4500 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 4501 } 4502 4503 N = pkg.services.size(); 4504 r = null; 4505 for (i=0; i<N; i++) { 4506 PackageParser.Service s = pkg.services.get(i); 4507 mServices.removeService(s); 4508 if (chatty) { 4509 if (r == null) { 4510 r = new StringBuilder(256); 4511 } else { 4512 r.append(' '); 4513 } 4514 r.append(s.info.name); 4515 } 4516 } 4517 if (r != null) { 4518 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 4519 } 4520 4521 N = pkg.receivers.size(); 4522 r = null; 4523 for (i=0; i<N; i++) { 4524 PackageParser.Activity a = pkg.receivers.get(i); 4525 mReceivers.removeActivity(a, "receiver"); 4526 if (chatty) { 4527 if (r == null) { 4528 r = new StringBuilder(256); 4529 } else { 4530 r.append(' '); 4531 } 4532 r.append(a.info.name); 4533 } 4534 } 4535 if (r != null) { 4536 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 4537 } 4538 4539 N = pkg.activities.size(); 4540 r = null; 4541 for (i=0; i<N; i++) { 4542 PackageParser.Activity a = pkg.activities.get(i); 4543 mActivities.removeActivity(a, "activity"); 4544 if (chatty) { 4545 if (r == null) { 4546 r = new StringBuilder(256); 4547 } else { 4548 r.append(' '); 4549 } 4550 r.append(a.info.name); 4551 } 4552 } 4553 if (r != null) { 4554 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 4555 } 4556 4557 N = pkg.permissions.size(); 4558 r = null; 4559 for (i=0; i<N; i++) { 4560 PackageParser.Permission p = pkg.permissions.get(i); 4561 BasePermission bp = mSettings.mPermissions.get(p.info.name); 4562 if (bp == null) { 4563 bp = mSettings.mPermissionTrees.get(p.info.name); 4564 } 4565 if (bp != null && bp.perm == p) { 4566 bp.perm = null; 4567 if (chatty) { 4568 if (r == null) { 4569 r = new StringBuilder(256); 4570 } else { 4571 r.append(' '); 4572 } 4573 r.append(p.info.name); 4574 } 4575 } 4576 } 4577 if (r != null) { 4578 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 4579 } 4580 4581 N = pkg.instrumentation.size(); 4582 r = null; 4583 for (i=0; i<N; i++) { 4584 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 4585 mInstrumentation.remove(a.getComponentName()); 4586 if (chatty) { 4587 if (r == null) { 4588 r = new StringBuilder(256); 4589 } else { 4590 r.append(' '); 4591 } 4592 r.append(a.info.name); 4593 } 4594 } 4595 if (r != null) { 4596 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 4597 } 4598 } 4599 } 4600 4601 private static final boolean isPackageFilename(String name) { 4602 return name != null && name.endsWith(".apk"); 4603 } 4604 4605 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 4606 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 4607 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 4608 return true; 4609 } 4610 } 4611 return false; 4612 } 4613 4614 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 4615 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 4616 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 4617 4618 private void updatePermissionsLPw(String changingPkg, 4619 PackageParser.Package pkgInfo, int flags) { 4620 // Make sure there are no dangling permission trees. 4621 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 4622 while (it.hasNext()) { 4623 final BasePermission bp = it.next(); 4624 if (bp.packageSetting == null) { 4625 // We may not yet have parsed the package, so just see if 4626 // we still know about its settings. 4627 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 4628 } 4629 if (bp.packageSetting == null) { 4630 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 4631 + " from package " + bp.sourcePackage); 4632 it.remove(); 4633 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 4634 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 4635 Slog.i(TAG, "Removing old permission tree: " + bp.name 4636 + " from package " + bp.sourcePackage); 4637 flags |= UPDATE_PERMISSIONS_ALL; 4638 it.remove(); 4639 } 4640 } 4641 } 4642 4643 // Make sure all dynamic permissions have been assigned to a package, 4644 // and make sure there are no dangling permissions. 4645 it = mSettings.mPermissions.values().iterator(); 4646 while (it.hasNext()) { 4647 final BasePermission bp = it.next(); 4648 if (bp.type == BasePermission.TYPE_DYNAMIC) { 4649 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 4650 + bp.name + " pkg=" + bp.sourcePackage 4651 + " info=" + bp.pendingInfo); 4652 if (bp.packageSetting == null && bp.pendingInfo != null) { 4653 final BasePermission tree = findPermissionTreeLP(bp.name); 4654 if (tree != null && tree.perm != null) { 4655 bp.packageSetting = tree.packageSetting; 4656 bp.perm = new PackageParser.Permission(tree.perm.owner, 4657 new PermissionInfo(bp.pendingInfo)); 4658 bp.perm.info.packageName = tree.perm.info.packageName; 4659 bp.perm.info.name = bp.name; 4660 bp.uid = tree.uid; 4661 } 4662 } 4663 } 4664 if (bp.packageSetting == null) { 4665 // We may not yet have parsed the package, so just see if 4666 // we still know about its settings. 4667 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 4668 } 4669 if (bp.packageSetting == null) { 4670 Slog.w(TAG, "Removing dangling permission: " + bp.name 4671 + " from package " + bp.sourcePackage); 4672 it.remove(); 4673 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 4674 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 4675 Slog.i(TAG, "Removing old permission: " + bp.name 4676 + " from package " + bp.sourcePackage); 4677 flags |= UPDATE_PERMISSIONS_ALL; 4678 it.remove(); 4679 } 4680 } 4681 } 4682 4683 // Now update the permissions for all packages, in particular 4684 // replace the granted permissions of the system packages. 4685 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 4686 for (PackageParser.Package pkg : mPackages.values()) { 4687 if (pkg != pkgInfo) { 4688 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 4689 } 4690 } 4691 } 4692 4693 if (pkgInfo != null) { 4694 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 4695 } 4696 } 4697 4698 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 4699 final PackageSetting ps = (PackageSetting) pkg.mExtras; 4700 if (ps == null) { 4701 return; 4702 } 4703 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 4704 HashSet<String> origPermissions = gp.grantedPermissions; 4705 boolean changedPermission = false; 4706 4707 if (replace) { 4708 ps.permissionsFixed = false; 4709 if (gp == ps) { 4710 origPermissions = new HashSet<String>(gp.grantedPermissions); 4711 gp.grantedPermissions.clear(); 4712 gp.gids = mGlobalGids; 4713 } 4714 } 4715 4716 if (gp.gids == null) { 4717 gp.gids = mGlobalGids; 4718 } 4719 4720 final int N = pkg.requestedPermissions.size(); 4721 for (int i=0; i<N; i++) { 4722 final String name = pkg.requestedPermissions.get(i); 4723 //final boolean required = pkg.requestedPermssionsRequired.get(i); 4724 final BasePermission bp = mSettings.mPermissions.get(name); 4725 if (DEBUG_INSTALL) { 4726 if (gp != ps) { 4727 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 4728 } 4729 } 4730 if (bp != null && bp.packageSetting != null) { 4731 final String perm = bp.name; 4732 boolean allowed; 4733 boolean allowedSig = false; 4734 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 4735 if (level == PermissionInfo.PROTECTION_NORMAL 4736 || level == PermissionInfo.PROTECTION_DANGEROUS) { 4737 allowed = true; 4738 } else if (bp.packageSetting == null) { 4739 // This permission is invalid; skip it. 4740 allowed = false; 4741 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 4742 allowed = (compareSignatures( 4743 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 4744 == PackageManager.SIGNATURE_MATCH) 4745 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 4746 == PackageManager.SIGNATURE_MATCH); 4747 if (!allowed && (bp.protectionLevel 4748 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 4749 if (isSystemApp(pkg)) { 4750 // For updated system applications, a system permission 4751 // is granted only if it had been defined by the original application. 4752 if (isUpdatedSystemApp(pkg)) { 4753 final PackageSetting sysPs = mSettings 4754 .getDisabledSystemPkgLPr(pkg.packageName); 4755 final GrantedPermissions origGp = sysPs.sharedUser != null 4756 ? sysPs.sharedUser : sysPs; 4757 if (origGp.grantedPermissions.contains(perm)) { 4758 allowed = true; 4759 } else { 4760 allowed = false; 4761 } 4762 } else { 4763 allowed = true; 4764 } 4765 } 4766 } 4767 if (!allowed && (bp.protectionLevel 4768 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 4769 // For development permissions, a development permission 4770 // is granted only if it was already granted. 4771 if (origPermissions.contains(perm)) { 4772 allowed = true; 4773 } else { 4774 allowed = false; 4775 } 4776 } 4777 if (allowed) { 4778 allowedSig = true; 4779 } 4780 } else { 4781 allowed = false; 4782 } 4783 if (DEBUG_INSTALL) { 4784 if (gp != ps) { 4785 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 4786 } 4787 } 4788 if (allowed) { 4789 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 4790 && ps.permissionsFixed) { 4791 // If this is an existing, non-system package, then 4792 // we can't add any new permissions to it. 4793 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 4794 allowed = false; 4795 // Except... if this is a permission that was added 4796 // to the platform (note: need to only do this when 4797 // updating the platform). 4798 final int NP = PackageParser.NEW_PERMISSIONS.length; 4799 for (int ip=0; ip<NP; ip++) { 4800 final PackageParser.NewPermissionInfo npi 4801 = PackageParser.NEW_PERMISSIONS[ip]; 4802 if (npi.name.equals(perm) 4803 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 4804 allowed = true; 4805 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 4806 + pkg.packageName); 4807 break; 4808 } 4809 } 4810 } 4811 } 4812 if (allowed) { 4813 if (!gp.grantedPermissions.contains(perm)) { 4814 changedPermission = true; 4815 gp.grantedPermissions.add(perm); 4816 gp.gids = appendInts(gp.gids, bp.gids); 4817 } else if (!ps.haveGids) { 4818 gp.gids = appendInts(gp.gids, bp.gids); 4819 } 4820 } else { 4821 Slog.w(TAG, "Not granting permission " + perm 4822 + " to package " + pkg.packageName 4823 + " because it was previously installed without"); 4824 } 4825 } else { 4826 if (gp.grantedPermissions.remove(perm)) { 4827 changedPermission = true; 4828 gp.gids = removeInts(gp.gids, bp.gids); 4829 Slog.i(TAG, "Un-granting permission " + perm 4830 + " from package " + pkg.packageName 4831 + " (protectionLevel=" + bp.protectionLevel 4832 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 4833 + ")"); 4834 } else { 4835 Slog.w(TAG, "Not granting permission " + perm 4836 + " to package " + pkg.packageName 4837 + " (protectionLevel=" + bp.protectionLevel 4838 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 4839 + ")"); 4840 } 4841 } 4842 } else { 4843 Slog.w(TAG, "Unknown permission " + name 4844 + " in package " + pkg.packageName); 4845 } 4846 } 4847 4848 if ((changedPermission || replace) && !ps.permissionsFixed && 4849 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) || 4850 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){ 4851 // This is the first that we have heard about this package, so the 4852 // permissions we have now selected are fixed until explicitly 4853 // changed. 4854 ps.permissionsFixed = true; 4855 } 4856 ps.haveGids = true; 4857 } 4858 4859 private final class ActivityIntentResolver 4860 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 4861 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 4862 boolean defaultOnly, int userId) { 4863 if (!sUserManager.exists(userId)) return null; 4864 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 4865 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 4866 } 4867 4868 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 4869 int userId) { 4870 if (!sUserManager.exists(userId)) return null; 4871 mFlags = flags; 4872 return super.queryIntent(intent, resolvedType, 4873 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 4874 } 4875 4876 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 4877 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 4878 if (!sUserManager.exists(userId)) return null; 4879 if (packageActivities == null) { 4880 return null; 4881 } 4882 mFlags = flags; 4883 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 4884 final int N = packageActivities.size(); 4885 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 4886 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 4887 4888 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 4889 for (int i = 0; i < N; ++i) { 4890 intentFilters = packageActivities.get(i).intents; 4891 if (intentFilters != null && intentFilters.size() > 0) { 4892 PackageParser.ActivityIntentInfo[] array = 4893 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 4894 intentFilters.toArray(array); 4895 listCut.add(array); 4896 } 4897 } 4898 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 4899 } 4900 4901 public final void addActivity(PackageParser.Activity a, String type) { 4902 final boolean systemApp = isSystemApp(a.info.applicationInfo); 4903 mActivities.put(a.getComponentName(), a); 4904 if (DEBUG_SHOW_INFO) 4905 Log.v( 4906 TAG, " " + type + " " + 4907 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 4908 if (DEBUG_SHOW_INFO) 4909 Log.v(TAG, " Class=" + a.info.name); 4910 final int NI = a.intents.size(); 4911 for (int j=0; j<NI; j++) { 4912 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 4913 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 4914 intent.setPriority(0); 4915 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 4916 + a.className + " with priority > 0, forcing to 0"); 4917 } 4918 if (DEBUG_SHOW_INFO) { 4919 Log.v(TAG, " IntentFilter:"); 4920 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 4921 } 4922 if (!intent.debugCheck()) { 4923 Log.w(TAG, "==> For Activity " + a.info.name); 4924 } 4925 addFilter(intent); 4926 } 4927 } 4928 4929 public final void removeActivity(PackageParser.Activity a, String type) { 4930 mActivities.remove(a.getComponentName()); 4931 if (DEBUG_SHOW_INFO) { 4932 Log.v(TAG, " " + type + " " 4933 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 4934 : a.info.name) + ":"); 4935 Log.v(TAG, " Class=" + a.info.name); 4936 } 4937 final int NI = a.intents.size(); 4938 for (int j=0; j<NI; j++) { 4939 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 4940 if (DEBUG_SHOW_INFO) { 4941 Log.v(TAG, " IntentFilter:"); 4942 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 4943 } 4944 removeFilter(intent); 4945 } 4946 } 4947 4948 @Override 4949 protected boolean allowFilterResult( 4950 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 4951 ActivityInfo filterAi = filter.activity.info; 4952 for (int i=dest.size()-1; i>=0; i--) { 4953 ActivityInfo destAi = dest.get(i).activityInfo; 4954 if (destAi.name == filterAi.name 4955 && destAi.packageName == filterAi.packageName) { 4956 return false; 4957 } 4958 } 4959 return true; 4960 } 4961 4962 @Override 4963 protected ActivityIntentInfo[] newArray(int size) { 4964 return new ActivityIntentInfo[size]; 4965 } 4966 4967 @Override 4968 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 4969 if (!sUserManager.exists(userId)) return true; 4970 PackageParser.Package p = filter.activity.owner; 4971 if (p != null) { 4972 PackageSetting ps = (PackageSetting)p.mExtras; 4973 if (ps != null) { 4974 // System apps are never considered stopped for purposes of 4975 // filtering, because there may be no way for the user to 4976 // actually re-launch them. 4977 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 4978 && ps.getStopped(userId); 4979 } 4980 } 4981 return false; 4982 } 4983 4984 @Override 4985 protected String packageForFilter(PackageParser.ActivityIntentInfo info) { 4986 return info.activity.owner.packageName; 4987 } 4988 4989 @Override 4990 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 4991 int match, int userId) { 4992 if (!sUserManager.exists(userId)) return null; 4993 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 4994 return null; 4995 } 4996 final PackageParser.Activity activity = info.activity; 4997 if (mSafeMode && (activity.info.applicationInfo.flags 4998 &ApplicationInfo.FLAG_SYSTEM) == 0) { 4999 return null; 5000 } 5001 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 5002 if (ps == null) { 5003 return null; 5004 } 5005 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 5006 ps.readUserState(userId), userId); 5007 if (ai == null) { 5008 return null; 5009 } 5010 final ResolveInfo res = new ResolveInfo(); 5011 res.activityInfo = ai; 5012 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 5013 res.filter = info; 5014 } 5015 res.priority = info.getPriority(); 5016 res.preferredOrder = activity.owner.mPreferredOrder; 5017 //System.out.println("Result: " + res.activityInfo.className + 5018 // " = " + res.priority); 5019 res.match = match; 5020 res.isDefault = info.hasDefault; 5021 res.labelRes = info.labelRes; 5022 res.nonLocalizedLabel = info.nonLocalizedLabel; 5023 res.icon = info.icon; 5024 res.system = isSystemApp(res.activityInfo.applicationInfo); 5025 return res; 5026 } 5027 5028 @Override 5029 protected void sortResults(List<ResolveInfo> results) { 5030 Collections.sort(results, mResolvePrioritySorter); 5031 } 5032 5033 @Override 5034 protected void dumpFilter(PrintWriter out, String prefix, 5035 PackageParser.ActivityIntentInfo filter) { 5036 out.print(prefix); out.print( 5037 Integer.toHexString(System.identityHashCode(filter.activity))); 5038 out.print(' '); 5039 out.print(filter.activity.getComponentShortName()); 5040 out.print(" filter "); 5041 out.println(Integer.toHexString(System.identityHashCode(filter))); 5042 } 5043 5044// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 5045// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 5046// final List<ResolveInfo> retList = Lists.newArrayList(); 5047// while (i.hasNext()) { 5048// final ResolveInfo resolveInfo = i.next(); 5049// if (isEnabledLP(resolveInfo.activityInfo)) { 5050// retList.add(resolveInfo); 5051// } 5052// } 5053// return retList; 5054// } 5055 5056 // Keys are String (activity class name), values are Activity. 5057 private final HashMap<ComponentName, PackageParser.Activity> mActivities 5058 = new HashMap<ComponentName, PackageParser.Activity>(); 5059 private int mFlags; 5060 } 5061 5062 private final class ServiceIntentResolver 5063 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 5064 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 5065 boolean defaultOnly, int userId) { 5066 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 5067 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 5068 } 5069 5070 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 5071 int userId) { 5072 if (!sUserManager.exists(userId)) return null; 5073 mFlags = flags; 5074 return super.queryIntent(intent, resolvedType, 5075 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 5076 } 5077 5078 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 5079 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 5080 if (!sUserManager.exists(userId)) return null; 5081 if (packageServices == null) { 5082 return null; 5083 } 5084 mFlags = flags; 5085 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 5086 final int N = packageServices.size(); 5087 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 5088 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 5089 5090 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 5091 for (int i = 0; i < N; ++i) { 5092 intentFilters = packageServices.get(i).intents; 5093 if (intentFilters != null && intentFilters.size() > 0) { 5094 PackageParser.ServiceIntentInfo[] array = 5095 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 5096 intentFilters.toArray(array); 5097 listCut.add(array); 5098 } 5099 } 5100 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 5101 } 5102 5103 public final void addService(PackageParser.Service s) { 5104 mServices.put(s.getComponentName(), s); 5105 if (DEBUG_SHOW_INFO) { 5106 Log.v(TAG, " " 5107 + (s.info.nonLocalizedLabel != null 5108 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 5109 Log.v(TAG, " Class=" + s.info.name); 5110 } 5111 final int NI = s.intents.size(); 5112 int j; 5113 for (j=0; j<NI; j++) { 5114 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 5115 if (DEBUG_SHOW_INFO) { 5116 Log.v(TAG, " IntentFilter:"); 5117 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5118 } 5119 if (!intent.debugCheck()) { 5120 Log.w(TAG, "==> For Service " + s.info.name); 5121 } 5122 addFilter(intent); 5123 } 5124 } 5125 5126 public final void removeService(PackageParser.Service s) { 5127 mServices.remove(s.getComponentName()); 5128 if (DEBUG_SHOW_INFO) { 5129 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 5130 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 5131 Log.v(TAG, " Class=" + s.info.name); 5132 } 5133 final int NI = s.intents.size(); 5134 int j; 5135 for (j=0; j<NI; j++) { 5136 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 5137 if (DEBUG_SHOW_INFO) { 5138 Log.v(TAG, " IntentFilter:"); 5139 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5140 } 5141 removeFilter(intent); 5142 } 5143 } 5144 5145 @Override 5146 protected boolean allowFilterResult( 5147 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 5148 ServiceInfo filterSi = filter.service.info; 5149 for (int i=dest.size()-1; i>=0; i--) { 5150 ServiceInfo destAi = dest.get(i).serviceInfo; 5151 if (destAi.name == filterSi.name 5152 && destAi.packageName == filterSi.packageName) { 5153 return false; 5154 } 5155 } 5156 return true; 5157 } 5158 5159 @Override 5160 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 5161 return new PackageParser.ServiceIntentInfo[size]; 5162 } 5163 5164 @Override 5165 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 5166 if (!sUserManager.exists(userId)) return true; 5167 PackageParser.Package p = filter.service.owner; 5168 if (p != null) { 5169 PackageSetting ps = (PackageSetting)p.mExtras; 5170 if (ps != null) { 5171 // System apps are never considered stopped for purposes of 5172 // filtering, because there may be no way for the user to 5173 // actually re-launch them. 5174 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 5175 && ps.getStopped(userId); 5176 } 5177 } 5178 return false; 5179 } 5180 5181 @Override 5182 protected String packageForFilter(PackageParser.ServiceIntentInfo info) { 5183 return info.service.owner.packageName; 5184 } 5185 5186 @Override 5187 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 5188 int match, int userId) { 5189 if (!sUserManager.exists(userId)) return null; 5190 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 5191 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 5192 return null; 5193 } 5194 final PackageParser.Service service = info.service; 5195 if (mSafeMode && (service.info.applicationInfo.flags 5196 &ApplicationInfo.FLAG_SYSTEM) == 0) { 5197 return null; 5198 } 5199 PackageSetting ps = (PackageSetting) service.owner.mExtras; 5200 if (ps == null) { 5201 return null; 5202 } 5203 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 5204 ps.readUserState(userId), userId); 5205 if (si == null) { 5206 return null; 5207 } 5208 final ResolveInfo res = new ResolveInfo(); 5209 res.serviceInfo = si; 5210 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 5211 res.filter = filter; 5212 } 5213 res.priority = info.getPriority(); 5214 res.preferredOrder = service.owner.mPreferredOrder; 5215 //System.out.println("Result: " + res.activityInfo.className + 5216 // " = " + res.priority); 5217 res.match = match; 5218 res.isDefault = info.hasDefault; 5219 res.labelRes = info.labelRes; 5220 res.nonLocalizedLabel = info.nonLocalizedLabel; 5221 res.icon = info.icon; 5222 res.system = isSystemApp(res.serviceInfo.applicationInfo); 5223 return res; 5224 } 5225 5226 @Override 5227 protected void sortResults(List<ResolveInfo> results) { 5228 Collections.sort(results, mResolvePrioritySorter); 5229 } 5230 5231 @Override 5232 protected void dumpFilter(PrintWriter out, String prefix, 5233 PackageParser.ServiceIntentInfo filter) { 5234 out.print(prefix); out.print( 5235 Integer.toHexString(System.identityHashCode(filter.service))); 5236 out.print(' '); 5237 out.print(filter.service.getComponentShortName()); 5238 out.print(" filter "); 5239 out.println(Integer.toHexString(System.identityHashCode(filter))); 5240 } 5241 5242// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 5243// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 5244// final List<ResolveInfo> retList = Lists.newArrayList(); 5245// while (i.hasNext()) { 5246// final ResolveInfo resolveInfo = (ResolveInfo) i; 5247// if (isEnabledLP(resolveInfo.serviceInfo)) { 5248// retList.add(resolveInfo); 5249// } 5250// } 5251// return retList; 5252// } 5253 5254 // Keys are String (activity class name), values are Activity. 5255 private final HashMap<ComponentName, PackageParser.Service> mServices 5256 = new HashMap<ComponentName, PackageParser.Service>(); 5257 private int mFlags; 5258 }; 5259 5260 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 5261 new Comparator<ResolveInfo>() { 5262 public int compare(ResolveInfo r1, ResolveInfo r2) { 5263 int v1 = r1.priority; 5264 int v2 = r2.priority; 5265 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 5266 if (v1 != v2) { 5267 return (v1 > v2) ? -1 : 1; 5268 } 5269 v1 = r1.preferredOrder; 5270 v2 = r2.preferredOrder; 5271 if (v1 != v2) { 5272 return (v1 > v2) ? -1 : 1; 5273 } 5274 if (r1.isDefault != r2.isDefault) { 5275 return r1.isDefault ? -1 : 1; 5276 } 5277 v1 = r1.match; 5278 v2 = r2.match; 5279 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 5280 if (v1 != v2) { 5281 return (v1 > v2) ? -1 : 1; 5282 } 5283 if (r1.system != r2.system) { 5284 return r1.system ? -1 : 1; 5285 } 5286 return 0; 5287 } 5288 }; 5289 5290 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 5291 new Comparator<ProviderInfo>() { 5292 public int compare(ProviderInfo p1, ProviderInfo p2) { 5293 final int v1 = p1.initOrder; 5294 final int v2 = p2.initOrder; 5295 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 5296 } 5297 }; 5298 5299 static final void sendPackageBroadcast(String action, String pkg, 5300 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 5301 int[] userIds) { 5302 IActivityManager am = ActivityManagerNative.getDefault(); 5303 if (am != null) { 5304 try { 5305 if (userIds == null) { 5306 userIds = sUserManager.getUserIds(); 5307 } 5308 for (int id : userIds) { 5309 final Intent intent = new Intent(action, 5310 pkg != null ? Uri.fromParts("package", pkg, null) : null); 5311 if (extras != null) { 5312 intent.putExtras(extras); 5313 } 5314 if (targetPkg != null) { 5315 intent.setPackage(targetPkg); 5316 } 5317 // Modify the UID when posting to other users 5318 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 5319 if (uid > 0 && UserHandle.getUserId(uid) != id) { 5320 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 5321 intent.putExtra(Intent.EXTRA_UID, uid); 5322 } 5323 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 5324 if (DEBUG_BROADCASTS) { 5325 RuntimeException here = new RuntimeException("here"); 5326 here.fillInStackTrace(); 5327 Slog.d(TAG, "Sending to user " + id + ": " 5328 + intent.toShortString(false, true, false, false) 5329 + " " + intent.getExtras(), here); 5330 } 5331 am.broadcastIntent(null, intent, null, finishedReceiver, 5332 0, null, null, null, finishedReceiver != null, false, id); 5333 } 5334 } catch (RemoteException ex) { 5335 } 5336 } 5337 } 5338 5339 /** 5340 * Check if the external storage media is available. This is true if there 5341 * is a mounted external storage medium or if the external storage is 5342 * emulated. 5343 */ 5344 private boolean isExternalMediaAvailable() { 5345 return mMediaMounted || Environment.isExternalStorageEmulated(); 5346 } 5347 5348 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 5349 // writer 5350 final int userId = UserHandle.getCallingUserId(); 5351 synchronized (mPackages) { 5352 if (!isExternalMediaAvailable()) { 5353 // If the external storage is no longer mounted at this point, 5354 // the caller may not have been able to delete all of this 5355 // packages files and can not delete any more. Bail. 5356 return null; 5357 } 5358 ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned.get(userId); 5359 if (pkgs != null) { 5360 if (lastPackage != null) { 5361 pkgs.remove(lastPackage); 5362 } 5363 if (pkgs.size() > 0) { 5364 return pkgs.get(0); 5365 } 5366 } 5367 mSettings.mPackagesToBeCleaned.remove(userId); 5368 } 5369 // Move on to the next user to clean. 5370 long ident = Binder.clearCallingIdentity(); 5371 try { 5372 startCleaningPackages(userId); 5373 } finally { 5374 Binder.restoreCallingIdentity(ident); 5375 } 5376 return null; 5377 } 5378 5379 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 5380 if (false) { 5381 RuntimeException here = new RuntimeException("here"); 5382 here.fillInStackTrace(); 5383 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 5384 + " andCode=" + andCode, here); 5385 } 5386 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 5387 userId, andCode ? 1 : 0, packageName)); 5388 } 5389 5390 void startCleaningPackages(int lastUser) { 5391 // reader 5392 int nextUser = -1; 5393 synchronized (mPackages) { 5394 if (!isExternalMediaAvailable()) { 5395 return; 5396 } 5397 final int N = mSettings.mPackagesToBeCleaned.size(); 5398 if (N <= 0) { 5399 return; 5400 } 5401 for (int i=0; i<N; i++) { 5402 int user = mSettings.mPackagesToBeCleaned.keyAt(i); 5403 if (user > lastUser) { 5404 nextUser = user; 5405 break; 5406 } 5407 } 5408 if (nextUser < 0) { 5409 nextUser = mSettings.mPackagesToBeCleaned.keyAt(0); 5410 } 5411 } 5412 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 5413 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 5414 IActivityManager am = ActivityManagerNative.getDefault(); 5415 if (am != null) { 5416 try { 5417 am.startService(null, intent, null, nextUser); 5418 } catch (RemoteException e) { 5419 } 5420 } 5421 } 5422 5423 private final class AppDirObserver extends FileObserver { 5424 public AppDirObserver(String path, int mask, boolean isrom) { 5425 super(path, mask); 5426 mRootDir = path; 5427 mIsRom = isrom; 5428 } 5429 5430 public void onEvent(int event, String path) { 5431 String removedPackage = null; 5432 int removedUid = -1; 5433 int[] removedUsers = null; 5434 String addedPackage = null; 5435 int addedUid = -1; 5436 int[] addedUsers = null; 5437 5438 // TODO post a message to the handler to obtain serial ordering 5439 synchronized (mInstallLock) { 5440 String fullPathStr = null; 5441 File fullPath = null; 5442 if (path != null) { 5443 fullPath = new File(mRootDir, path); 5444 fullPathStr = fullPath.getPath(); 5445 } 5446 5447 if (DEBUG_APP_DIR_OBSERVER) 5448 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 5449 5450 if (!isPackageFilename(path)) { 5451 if (DEBUG_APP_DIR_OBSERVER) 5452 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 5453 return; 5454 } 5455 5456 // Ignore packages that are being installed or 5457 // have just been installed. 5458 if (ignoreCodePath(fullPathStr)) { 5459 return; 5460 } 5461 PackageParser.Package p = null; 5462 // reader 5463 synchronized (mPackages) { 5464 p = mAppDirs.get(fullPathStr); 5465 if (p != null) { 5466 PackageSetting ps = mSettings.mPackages.get(p.applicationInfo.packageName); 5467 if (ps != null) { 5468 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 5469 } else { 5470 removedUsers = sUserManager.getUserIds(); 5471 } 5472 } 5473 addedUsers = sUserManager.getUserIds(); 5474 } 5475 if ((event&REMOVE_EVENTS) != 0) { 5476 if (p != null) { 5477 removePackageLI(p, true); 5478 removedPackage = p.applicationInfo.packageName; 5479 removedUid = p.applicationInfo.uid; 5480 } 5481 } 5482 5483 if ((event&ADD_EVENTS) != 0) { 5484 if (p == null) { 5485 p = scanPackageLI(fullPath, 5486 (mIsRom ? PackageParser.PARSE_IS_SYSTEM 5487 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) | 5488 PackageParser.PARSE_CHATTY | 5489 PackageParser.PARSE_MUST_BE_APK, 5490 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 5491 System.currentTimeMillis(), UserHandle.ALL); 5492 if (p != null) { 5493 /* 5494 * TODO this seems dangerous as the package may have 5495 * changed since we last acquired the mPackages 5496 * lock. 5497 */ 5498 // writer 5499 synchronized (mPackages) { 5500 updatePermissionsLPw(p.packageName, p, 5501 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 5502 } 5503 addedPackage = p.applicationInfo.packageName; 5504 addedUid = p.applicationInfo.uid; 5505 } 5506 } 5507 } 5508 5509 // reader 5510 synchronized (mPackages) { 5511 mSettings.writeLPr(); 5512 } 5513 } 5514 5515 if (removedPackage != null) { 5516 Bundle extras = new Bundle(1); 5517 extras.putInt(Intent.EXTRA_UID, removedUid); 5518 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 5519 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 5520 extras, null, null, removedUsers); 5521 } 5522 if (addedPackage != null) { 5523 Bundle extras = new Bundle(1); 5524 extras.putInt(Intent.EXTRA_UID, addedUid); 5525 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 5526 extras, null, null, addedUsers); 5527 } 5528 } 5529 5530 private final String mRootDir; 5531 private final boolean mIsRom; 5532 } 5533 5534 /* Called when a downloaded package installation has been confirmed by the user */ 5535 public void installPackage( 5536 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 5537 installPackage(packageURI, observer, flags, null); 5538 } 5539 5540 /* Called when a downloaded package installation has been confirmed by the user */ 5541 public void installPackage( 5542 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 5543 final String installerPackageName) { 5544 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null, 5545 null, null); 5546 } 5547 5548 @Override 5549 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 5550 int flags, String installerPackageName, Uri verificationURI, 5551 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 5552 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 5553 manifestDigest); 5554 installPackageWithVerificationAndEncryption(packageURI, observer, flags, 5555 installerPackageName, verificationParams, encryptionParams); 5556 } 5557 5558 public void installPackageWithVerificationAndEncryption(Uri packageURI, 5559 IPackageInstallObserver observer, int flags, String installerPackageName, 5560 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 5561 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 5562 null); 5563 5564 final int uid = Binder.getCallingUid(); 5565 UserHandle user; 5566 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 5567 user = UserHandle.ALL; 5568 } else { 5569 user = new UserHandle(UserHandle.getUserId(uid)); 5570 } 5571 5572 final int filteredFlags; 5573 5574 if (uid == Process.SHELL_UID || uid == 0) { 5575 if (DEBUG_INSTALL) { 5576 Slog.v(TAG, "Install from ADB"); 5577 } 5578 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 5579 } else { 5580 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 5581 } 5582 5583 final Message msg = mHandler.obtainMessage(INIT_COPY); 5584 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName, 5585 verificationParams, encryptionParams, user); 5586 mHandler.sendMessage(msg); 5587 } 5588 5589 /** 5590 * @hide 5591 */ 5592 @Override 5593 public int installExistingPackage(String packageName) { 5594 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 5595 null); 5596 PackageSetting pkgSetting; 5597 final int uid = Binder.getCallingUid(); 5598 final int userId = UserHandle.getUserId(uid); 5599 5600 long callingId = Binder.clearCallingIdentity(); 5601 try { 5602 boolean sendAdded = false; 5603 Bundle extras = new Bundle(1); 5604 5605 // writer 5606 synchronized (mPackages) { 5607 pkgSetting = mSettings.mPackages.get(packageName); 5608 if (pkgSetting == null) { 5609 return PackageManager.INSTALL_FAILED_INVALID_URI; 5610 } 5611 if (!pkgSetting.getInstalled(userId)) { 5612 pkgSetting.setInstalled(true, userId); 5613 mSettings.writePackageRestrictionsLPr(userId); 5614 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 5615 sendAdded = true; 5616 } 5617 } 5618 5619 if (sendAdded) { 5620 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 5621 packageName, extras, null, null, new int[] {userId}); 5622 } 5623 } finally { 5624 Binder.restoreCallingIdentity(callingId); 5625 } 5626 5627 return PackageManager.INSTALL_SUCCEEDED; 5628 } 5629 5630 @Override 5631 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 5632 mContext.enforceCallingOrSelfPermission( 5633 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 5634 "Only package verification agents can verify applications"); 5635 5636 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 5637 final PackageVerificationResponse response = new PackageVerificationResponse( 5638 verificationCode, Binder.getCallingUid()); 5639 msg.arg1 = id; 5640 msg.obj = response; 5641 mHandler.sendMessage(msg); 5642 } 5643 5644 @Override 5645 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 5646 long millisecondsToDelay) { 5647 mContext.enforceCallingOrSelfPermission( 5648 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 5649 "Only package verification agents can extend verification timeouts"); 5650 5651 final PackageVerificationState state = mPendingVerification.get(id); 5652 final PackageVerificationResponse response = new PackageVerificationResponse( 5653 verificationCodeAtTimeout, Binder.getCallingUid()); 5654 5655 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 5656 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 5657 } 5658 if (millisecondsToDelay < 0) { 5659 millisecondsToDelay = 0; 5660 } 5661 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 5662 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 5663 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 5664 } 5665 5666 if ((state != null) && !state.timeoutExtended()) { 5667 state.extendTimeout(); 5668 5669 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 5670 msg.arg1 = id; 5671 msg.obj = response; 5672 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 5673 } 5674 } 5675 5676 private void broadcastPackageVerified(int verificationId, Uri packageUri, 5677 int verificationCode) { 5678 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 5679 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 5680 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 5681 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 5682 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 5683 5684 mContext.sendBroadcast(intent, android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 5685 } 5686 5687 private ComponentName matchComponentForVerifier(String packageName, 5688 List<ResolveInfo> receivers) { 5689 ActivityInfo targetReceiver = null; 5690 5691 final int NR = receivers.size(); 5692 for (int i = 0; i < NR; i++) { 5693 final ResolveInfo info = receivers.get(i); 5694 if (info.activityInfo == null) { 5695 continue; 5696 } 5697 5698 if (packageName.equals(info.activityInfo.packageName)) { 5699 targetReceiver = info.activityInfo; 5700 break; 5701 } 5702 } 5703 5704 if (targetReceiver == null) { 5705 return null; 5706 } 5707 5708 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 5709 } 5710 5711 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 5712 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 5713 if (pkgInfo.verifiers.length == 0) { 5714 return null; 5715 } 5716 5717 final int N = pkgInfo.verifiers.length; 5718 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 5719 for (int i = 0; i < N; i++) { 5720 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 5721 5722 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 5723 receivers); 5724 if (comp == null) { 5725 continue; 5726 } 5727 5728 final int verifierUid = getUidForVerifier(verifierInfo); 5729 if (verifierUid == -1) { 5730 continue; 5731 } 5732 5733 if (DEBUG_VERIFY) { 5734 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 5735 + " with the correct signature"); 5736 } 5737 sufficientVerifiers.add(comp); 5738 verificationState.addSufficientVerifier(verifierUid); 5739 } 5740 5741 return sufficientVerifiers; 5742 } 5743 5744 private int getUidForVerifier(VerifierInfo verifierInfo) { 5745 synchronized (mPackages) { 5746 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 5747 if (pkg == null) { 5748 return -1; 5749 } else if (pkg.mSignatures.length != 1) { 5750 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 5751 + " has more than one signature; ignoring"); 5752 return -1; 5753 } 5754 5755 /* 5756 * If the public key of the package's signature does not match 5757 * our expected public key, then this is a different package and 5758 * we should skip. 5759 */ 5760 5761 final byte[] expectedPublicKey; 5762 try { 5763 final Signature verifierSig = pkg.mSignatures[0]; 5764 final PublicKey publicKey = verifierSig.getPublicKey(); 5765 expectedPublicKey = publicKey.getEncoded(); 5766 } catch (CertificateException e) { 5767 return -1; 5768 } 5769 5770 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 5771 5772 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 5773 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 5774 + " does not have the expected public key; ignoring"); 5775 return -1; 5776 } 5777 5778 return pkg.applicationInfo.uid; 5779 } 5780 } 5781 5782 public void finishPackageInstall(int token) { 5783 enforceSystemOrRoot("Only the system is allowed to finish installs"); 5784 5785 if (DEBUG_INSTALL) { 5786 Slog.v(TAG, "BM finishing package install for " + token); 5787 } 5788 5789 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 5790 mHandler.sendMessage(msg); 5791 } 5792 5793 /** 5794 * Get the verification agent timeout. 5795 * 5796 * @return verification timeout in milliseconds 5797 */ 5798 private long getVerificationTimeout() { 5799 return android.provider.Settings.Secure.getLong(mContext.getContentResolver(), 5800 android.provider.Settings.Secure.PACKAGE_VERIFIER_TIMEOUT, 5801 DEFAULT_VERIFICATION_TIMEOUT); 5802 } 5803 5804 /** 5805 * Get the default verification agent response code. 5806 * 5807 * @return default verification response code 5808 */ 5809 private int getDefaultVerificationResponse() { 5810 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 5811 android.provider.Settings.Secure.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 5812 DEFAULT_VERIFICATION_RESPONSE); 5813 } 5814 5815 /** 5816 * Check whether or not package verification has been enabled. 5817 * 5818 * @return true if verification should be performed 5819 */ 5820 private boolean isVerificationEnabled() { 5821 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 5822 android.provider.Settings.Secure.PACKAGE_VERIFIER_ENABLE, 5823 DEFAULT_VERIFY_ENABLE ? 1 : 0) == 1 ? true : false; 5824 } 5825 5826 /** 5827 * Get the "allow unknown sources" setting. 5828 * 5829 * @return the current "allow unknown sources" setting 5830 */ 5831 private int getUnknownSourcesSettings() { 5832 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 5833 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 5834 -1); 5835 } 5836 5837 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 5838 final int uid = Binder.getCallingUid(); 5839 // writer 5840 synchronized (mPackages) { 5841 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 5842 if (targetPackageSetting == null) { 5843 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 5844 } 5845 5846 PackageSetting installerPackageSetting; 5847 if (installerPackageName != null) { 5848 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 5849 if (installerPackageSetting == null) { 5850 throw new IllegalArgumentException("Unknown installer package: " 5851 + installerPackageName); 5852 } 5853 } else { 5854 installerPackageSetting = null; 5855 } 5856 5857 Signature[] callerSignature; 5858 Object obj = mSettings.getUserIdLPr(uid); 5859 if (obj != null) { 5860 if (obj instanceof SharedUserSetting) { 5861 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 5862 } else if (obj instanceof PackageSetting) { 5863 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 5864 } else { 5865 throw new SecurityException("Bad object " + obj + " for uid " + uid); 5866 } 5867 } else { 5868 throw new SecurityException("Unknown calling uid " + uid); 5869 } 5870 5871 // Verify: can't set installerPackageName to a package that is 5872 // not signed with the same cert as the caller. 5873 if (installerPackageSetting != null) { 5874 if (compareSignatures(callerSignature, 5875 installerPackageSetting.signatures.mSignatures) 5876 != PackageManager.SIGNATURE_MATCH) { 5877 throw new SecurityException( 5878 "Caller does not have same cert as new installer package " 5879 + installerPackageName); 5880 } 5881 } 5882 5883 // Verify: if target already has an installer package, it must 5884 // be signed with the same cert as the caller. 5885 if (targetPackageSetting.installerPackageName != null) { 5886 PackageSetting setting = mSettings.mPackages.get( 5887 targetPackageSetting.installerPackageName); 5888 // If the currently set package isn't valid, then it's always 5889 // okay to change it. 5890 if (setting != null) { 5891 if (compareSignatures(callerSignature, 5892 setting.signatures.mSignatures) 5893 != PackageManager.SIGNATURE_MATCH) { 5894 throw new SecurityException( 5895 "Caller does not have same cert as old installer package " 5896 + targetPackageSetting.installerPackageName); 5897 } 5898 } 5899 } 5900 5901 // Okay! 5902 targetPackageSetting.installerPackageName = installerPackageName; 5903 scheduleWriteSettingsLocked(); 5904 } 5905 } 5906 5907 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 5908 // Queue up an async operation since the package installation may take a little while. 5909 mHandler.post(new Runnable() { 5910 public void run() { 5911 mHandler.removeCallbacks(this); 5912 // Result object to be returned 5913 PackageInstalledInfo res = new PackageInstalledInfo(); 5914 res.returnCode = currentStatus; 5915 res.uid = -1; 5916 res.pkg = null; 5917 res.removedInfo = new PackageRemovedInfo(); 5918 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 5919 args.doPreInstall(res.returnCode); 5920 synchronized (mInstallLock) { 5921 installPackageLI(args, true, res); 5922 } 5923 args.doPostInstall(res.returnCode, res.uid); 5924 } 5925 5926 // A restore should be performed at this point if (a) the install 5927 // succeeded, (b) the operation is not an update, and (c) the new 5928 // package has a backupAgent defined. 5929 final boolean update = res.removedInfo.removedPackage != null; 5930 boolean doRestore = (!update 5931 && res.pkg != null 5932 && res.pkg.applicationInfo.backupAgentName != null); 5933 5934 // Set up the post-install work request bookkeeping. This will be used 5935 // and cleaned up by the post-install event handling regardless of whether 5936 // there's a restore pass performed. Token values are >= 1. 5937 int token; 5938 if (mNextInstallToken < 0) mNextInstallToken = 1; 5939 token = mNextInstallToken++; 5940 5941 PostInstallData data = new PostInstallData(args, res); 5942 mRunningInstalls.put(token, data); 5943 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 5944 5945 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 5946 // Pass responsibility to the Backup Manager. It will perform a 5947 // restore if appropriate, then pass responsibility back to the 5948 // Package Manager to run the post-install observer callbacks 5949 // and broadcasts. 5950 IBackupManager bm = IBackupManager.Stub.asInterface( 5951 ServiceManager.getService(Context.BACKUP_SERVICE)); 5952 if (bm != null) { 5953 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 5954 + " to BM for possible restore"); 5955 try { 5956 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 5957 } catch (RemoteException e) { 5958 // can't happen; the backup manager is local 5959 } catch (Exception e) { 5960 Slog.e(TAG, "Exception trying to enqueue restore", e); 5961 doRestore = false; 5962 } 5963 } else { 5964 Slog.e(TAG, "Backup Manager not found!"); 5965 doRestore = false; 5966 } 5967 } 5968 5969 if (!doRestore) { 5970 // No restore possible, or the Backup Manager was mysteriously not 5971 // available -- just fire the post-install work request directly. 5972 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 5973 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 5974 mHandler.sendMessage(msg); 5975 } 5976 } 5977 }); 5978 } 5979 5980 private abstract class HandlerParams { 5981 private static final int MAX_RETRIES = 4; 5982 5983 /** 5984 * Number of times startCopy() has been attempted and had a non-fatal 5985 * error. 5986 */ 5987 private int mRetries = 0; 5988 5989 /** User handle for the user requesting the information or installation. */ 5990 private final UserHandle mUser; 5991 5992 HandlerParams(UserHandle user) { 5993 mUser = user; 5994 } 5995 5996 UserHandle getUser() { 5997 return mUser; 5998 } 5999 6000 final boolean startCopy() { 6001 boolean res; 6002 try { 6003 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy"); 6004 6005 if (++mRetries > MAX_RETRIES) { 6006 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 6007 mHandler.sendEmptyMessage(MCS_GIVE_UP); 6008 handleServiceError(); 6009 return false; 6010 } else { 6011 handleStartCopy(); 6012 res = true; 6013 } 6014 } catch (RemoteException e) { 6015 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 6016 mHandler.sendEmptyMessage(MCS_RECONNECT); 6017 res = false; 6018 } 6019 handleReturnCode(); 6020 return res; 6021 } 6022 6023 final void serviceError() { 6024 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 6025 handleServiceError(); 6026 handleReturnCode(); 6027 } 6028 6029 abstract void handleStartCopy() throws RemoteException; 6030 abstract void handleServiceError(); 6031 abstract void handleReturnCode(); 6032 } 6033 6034 class MeasureParams extends HandlerParams { 6035 private final PackageStats mStats; 6036 private boolean mSuccess; 6037 6038 private final IPackageStatsObserver mObserver; 6039 6040 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 6041 super(new UserHandle(stats.userHandle)); 6042 mObserver = observer; 6043 mStats = stats; 6044 } 6045 6046 @Override 6047 void handleStartCopy() throws RemoteException { 6048 synchronized (mInstallLock) { 6049 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 6050 } 6051 6052 final boolean mounted; 6053 if (Environment.isExternalStorageEmulated()) { 6054 mounted = true; 6055 } else { 6056 final String status = Environment.getExternalStorageState(); 6057 6058 mounted = status.equals(Environment.MEDIA_MOUNTED) 6059 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 6060 } 6061 6062 if (mounted) { 6063 final File externalCacheDir = Environment 6064 .getExternalStorageAppCacheDirectory(mStats.packageName); 6065 final long externalCacheSize = mContainerService 6066 .calculateDirectorySize(externalCacheDir.getPath()); 6067 mStats.externalCacheSize = externalCacheSize; 6068 6069 final File externalDataDir = Environment 6070 .getExternalStorageAppDataDirectory(mStats.packageName); 6071 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir 6072 .getPath()); 6073 6074 if (externalCacheDir.getParentFile().equals(externalDataDir)) { 6075 externalDataSize -= externalCacheSize; 6076 } 6077 mStats.externalDataSize = externalDataSize; 6078 6079 final File externalMediaDir = Environment 6080 .getExternalStorageAppMediaDirectory(mStats.packageName); 6081 mStats.externalMediaSize = mContainerService 6082 .calculateDirectorySize(externalMediaDir.getPath()); 6083 6084 final File externalObbDir = Environment 6085 .getExternalStorageAppObbDirectory(mStats.packageName); 6086 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir 6087 .getPath()); 6088 } 6089 } 6090 6091 @Override 6092 void handleReturnCode() { 6093 if (mObserver != null) { 6094 try { 6095 mObserver.onGetStatsCompleted(mStats, mSuccess); 6096 } catch (RemoteException e) { 6097 Slog.i(TAG, "Observer no longer exists."); 6098 } 6099 } 6100 } 6101 6102 @Override 6103 void handleServiceError() { 6104 Slog.e(TAG, "Could not measure application " + mStats.packageName 6105 + " external storage"); 6106 } 6107 } 6108 6109 class InstallParams extends HandlerParams { 6110 final IPackageInstallObserver observer; 6111 int flags; 6112 6113 private final Uri mPackageURI; 6114 final String installerPackageName; 6115 final VerificationParams verificationParams; 6116 private InstallArgs mArgs; 6117 private int mRet; 6118 private File mTempPackage; 6119 final ContainerEncryptionParams encryptionParams; 6120 6121 InstallParams(Uri packageURI, 6122 IPackageInstallObserver observer, int flags, 6123 String installerPackageName, VerificationParams verificationParams, 6124 ContainerEncryptionParams encryptionParams, UserHandle user) { 6125 super(user); 6126 this.mPackageURI = packageURI; 6127 this.flags = flags; 6128 this.observer = observer; 6129 this.installerPackageName = installerPackageName; 6130 this.verificationParams = verificationParams; 6131 this.encryptionParams = encryptionParams; 6132 } 6133 6134 public ManifestDigest getManifestDigest() { 6135 if (verificationParams == null) { 6136 return null; 6137 } 6138 return verificationParams.getManifestDigest(); 6139 } 6140 6141 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 6142 String packageName = pkgLite.packageName; 6143 int installLocation = pkgLite.installLocation; 6144 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 6145 // reader 6146 synchronized (mPackages) { 6147 PackageParser.Package pkg = mPackages.get(packageName); 6148 if (pkg != null) { 6149 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 6150 // Check for downgrading. 6151 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 6152 if (pkgLite.versionCode < pkg.mVersionCode) { 6153 Slog.w(TAG, "Can't install update of " + packageName 6154 + " update version " + pkgLite.versionCode 6155 + " is older than installed version " 6156 + pkg.mVersionCode); 6157 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 6158 } 6159 } 6160 // Check for updated system application. 6161 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 6162 if (onSd) { 6163 Slog.w(TAG, "Cannot install update to system app on sdcard"); 6164 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 6165 } 6166 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6167 } else { 6168 if (onSd) { 6169 // Install flag overrides everything. 6170 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6171 } 6172 // If current upgrade specifies particular preference 6173 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 6174 // Application explicitly specified internal. 6175 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6176 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 6177 // App explictly prefers external. Let policy decide 6178 } else { 6179 // Prefer previous location 6180 if (isExternal(pkg)) { 6181 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6182 } 6183 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6184 } 6185 } 6186 } else { 6187 // Invalid install. Return error code 6188 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 6189 } 6190 } 6191 } 6192 // All the special cases have been taken care of. 6193 // Return result based on recommended install location. 6194 if (onSd) { 6195 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6196 } 6197 return pkgLite.recommendedInstallLocation; 6198 } 6199 6200 /* 6201 * Invoke remote method to get package information and install 6202 * location values. Override install location based on default 6203 * policy if needed and then create install arguments based 6204 * on the install location. 6205 */ 6206 public void handleStartCopy() throws RemoteException { 6207 int ret = PackageManager.INSTALL_SUCCEEDED; 6208 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 6209 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 6210 PackageInfoLite pkgLite = null; 6211 6212 if (onInt && onSd) { 6213 // Check if both bits are set. 6214 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 6215 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 6216 } else { 6217 final long lowThreshold; 6218 6219 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 6220 .getService(DeviceStorageMonitorService.SERVICE); 6221 if (dsm == null) { 6222 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 6223 lowThreshold = 0L; 6224 } else { 6225 lowThreshold = dsm.getMemoryLowThreshold(); 6226 } 6227 6228 try { 6229 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 6230 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6231 6232 final File packageFile; 6233 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 6234 ParcelFileDescriptor out = null; 6235 6236 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 6237 if (mTempPackage != null) { 6238 try { 6239 out = ParcelFileDescriptor.open(mTempPackage, 6240 ParcelFileDescriptor.MODE_READ_WRITE); 6241 } catch (FileNotFoundException e) { 6242 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 6243 } 6244 6245 // Make a temporary file for decryption. 6246 ret = mContainerService 6247 .copyResource(mPackageURI, encryptionParams, out); 6248 6249 packageFile = mTempPackage; 6250 6251 FileUtils.setPermissions(packageFile.getAbsolutePath(), 6252 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IROTH, 6253 -1, -1); 6254 } else { 6255 packageFile = null; 6256 } 6257 } else { 6258 packageFile = new File(mPackageURI.getPath()); 6259 } 6260 6261 if (packageFile != null) { 6262 // Remote call to find out default install location 6263 pkgLite = mContainerService.getMinimalPackageInfo( 6264 packageFile.getAbsolutePath(), flags, lowThreshold); 6265 } 6266 } finally { 6267 mContext.revokeUriPermission(mPackageURI, 6268 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6269 } 6270 } 6271 6272 if (ret == PackageManager.INSTALL_SUCCEEDED) { 6273 int loc = pkgLite.recommendedInstallLocation; 6274 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 6275 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 6276 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 6277 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 6278 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 6279 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6280 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 6281 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 6282 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 6283 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 6284 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 6285 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 6286 } else if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 6287 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 6288 } else { 6289 // Override with defaults if needed. 6290 loc = installLocationPolicy(pkgLite, flags); 6291 if (!onSd && !onInt) { 6292 // Override install location with flags 6293 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 6294 // Set the flag to install on external media. 6295 flags |= PackageManager.INSTALL_EXTERNAL; 6296 flags &= ~PackageManager.INSTALL_INTERNAL; 6297 } else { 6298 // Make sure the flag for installing on external 6299 // media is unset 6300 flags |= PackageManager.INSTALL_INTERNAL; 6301 flags &= ~PackageManager.INSTALL_EXTERNAL; 6302 } 6303 } 6304 } 6305 } 6306 6307 final InstallArgs args = createInstallArgs(this); 6308 mArgs = args; 6309 6310 if (ret == PackageManager.INSTALL_SUCCEEDED) { 6311 /* 6312 * Determine if we have any installed package verifiers. If we 6313 * do, then we'll defer to them to verify the packages. 6314 */ 6315 final int requiredUid = mRequiredVerifierPackage == null ? -1 6316 : getPackageUid(mRequiredVerifierPackage, 0); 6317 if (requiredUid != -1 && isVerificationEnabled()) { 6318 final Intent verification = new Intent( 6319 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 6320 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 6321 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6322 6323 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 6324 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 6325 0 /* TODO: Which userId? */); 6326 6327 if (DEBUG_VERIFY) { 6328 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 6329 + verification.toString() + " with " + pkgLite.verifiers.length 6330 + " optional verifiers"); 6331 } 6332 6333 final int verificationId = mPendingVerificationToken++; 6334 6335 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 6336 6337 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 6338 installerPackageName); 6339 6340 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 6341 6342 if (verificationParams != null) { 6343 if (verificationParams.getVerificationURI() != null) { 6344 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 6345 verificationParams.getVerificationURI()); 6346 } 6347 if (verificationParams.getOriginatingURI() != null) { 6348 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 6349 verificationParams.getOriginatingURI()); 6350 } 6351 if (verificationParams.getReferrer() != null) { 6352 verification.putExtra(Intent.EXTRA_REFERRER, 6353 verificationParams.getReferrer()); 6354 } 6355 } 6356 6357 final PackageVerificationState verificationState = new PackageVerificationState( 6358 requiredUid, args); 6359 6360 mPendingVerification.append(verificationId, verificationState); 6361 6362 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 6363 receivers, verificationState); 6364 6365 /* 6366 * If any sufficient verifiers were listed in the package 6367 * manifest, attempt to ask them. 6368 */ 6369 if (sufficientVerifiers != null) { 6370 final int N = sufficientVerifiers.size(); 6371 if (N == 0) { 6372 Slog.i(TAG, "Additional verifiers required, but none installed."); 6373 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 6374 } else { 6375 for (int i = 0; i < N; i++) { 6376 final ComponentName verifierComponent = sufficientVerifiers.get(i); 6377 6378 final Intent sufficientIntent = new Intent(verification); 6379 sufficientIntent.setComponent(verifierComponent); 6380 6381 mContext.sendBroadcast(sufficientIntent); 6382 } 6383 } 6384 } 6385 6386 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 6387 mRequiredVerifierPackage, receivers); 6388 if (ret == PackageManager.INSTALL_SUCCEEDED 6389 && mRequiredVerifierPackage != null) { 6390 /* 6391 * Send the intent to the required verification agent, 6392 * but only start the verification timeout after the 6393 * target BroadcastReceivers have run. 6394 */ 6395 verification.setComponent(requiredVerifierComponent); 6396 mContext.sendOrderedBroadcast(verification, 6397 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 6398 new BroadcastReceiver() { 6399 @Override 6400 public void onReceive(Context context, Intent intent) { 6401 final Message msg = mHandler 6402 .obtainMessage(CHECK_PENDING_VERIFICATION); 6403 msg.arg1 = verificationId; 6404 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 6405 } 6406 }, null, 0, null, null); 6407 6408 /* 6409 * We don't want the copy to proceed until verification 6410 * succeeds, so null out this field. 6411 */ 6412 mArgs = null; 6413 } 6414 } else { 6415 /* 6416 * No package verification is enabled, so immediately start 6417 * the remote call to initiate copy using temporary file. 6418 */ 6419 ret = args.copyApk(mContainerService, true); 6420 } 6421 } 6422 6423 mRet = ret; 6424 } 6425 6426 @Override 6427 void handleReturnCode() { 6428 // If mArgs is null, then MCS couldn't be reached. When it 6429 // reconnects, it will try again to install. At that point, this 6430 // will succeed. 6431 if (mArgs != null) { 6432 processPendingInstall(mArgs, mRet); 6433 } 6434 6435 if (mTempPackage != null) { 6436 if (!mTempPackage.delete()) { 6437 Slog.w(TAG, "Couldn't delete temporary file: " 6438 + mTempPackage.getAbsolutePath()); 6439 } 6440 } 6441 } 6442 6443 @Override 6444 void handleServiceError() { 6445 mArgs = createInstallArgs(this); 6446 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6447 } 6448 6449 public boolean isForwardLocked() { 6450 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6451 } 6452 6453 public Uri getPackageUri() { 6454 if (mTempPackage != null) { 6455 return Uri.fromFile(mTempPackage); 6456 } else { 6457 return mPackageURI; 6458 } 6459 } 6460 } 6461 6462 /* 6463 * Utility class used in movePackage api. 6464 * srcArgs and targetArgs are not set for invalid flags and make 6465 * sure to do null checks when invoking methods on them. 6466 * We probably want to return ErrorPrams for both failed installs 6467 * and moves. 6468 */ 6469 class MoveParams extends HandlerParams { 6470 final IPackageMoveObserver observer; 6471 final int flags; 6472 final String packageName; 6473 final InstallArgs srcArgs; 6474 final InstallArgs targetArgs; 6475 int uid; 6476 int mRet; 6477 6478 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 6479 String packageName, String dataDir, int uid, UserHandle user) { 6480 super(user); 6481 this.srcArgs = srcArgs; 6482 this.observer = observer; 6483 this.flags = flags; 6484 this.packageName = packageName; 6485 this.uid = uid; 6486 if (srcArgs != null) { 6487 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 6488 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir); 6489 } else { 6490 targetArgs = null; 6491 } 6492 } 6493 6494 public void handleStartCopy() throws RemoteException { 6495 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6496 // Check for storage space on target medium 6497 if (!targetArgs.checkFreeStorage(mContainerService)) { 6498 Log.w(TAG, "Insufficient storage to install"); 6499 return; 6500 } 6501 6502 mRet = srcArgs.doPreCopy(); 6503 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6504 return; 6505 } 6506 6507 mRet = targetArgs.copyApk(mContainerService, false); 6508 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6509 srcArgs.doPostCopy(uid); 6510 return; 6511 } 6512 6513 mRet = srcArgs.doPostCopy(uid); 6514 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6515 return; 6516 } 6517 6518 mRet = targetArgs.doPreInstall(mRet); 6519 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6520 return; 6521 } 6522 6523 if (DEBUG_SD_INSTALL) { 6524 StringBuilder builder = new StringBuilder(); 6525 if (srcArgs != null) { 6526 builder.append("src: "); 6527 builder.append(srcArgs.getCodePath()); 6528 } 6529 if (targetArgs != null) { 6530 builder.append(" target : "); 6531 builder.append(targetArgs.getCodePath()); 6532 } 6533 Log.i(TAG, builder.toString()); 6534 } 6535 } 6536 6537 @Override 6538 void handleReturnCode() { 6539 targetArgs.doPostInstall(mRet, uid); 6540 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 6541 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 6542 currentStatus = PackageManager.MOVE_SUCCEEDED; 6543 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 6544 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 6545 } 6546 processPendingMove(this, currentStatus); 6547 } 6548 6549 @Override 6550 void handleServiceError() { 6551 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6552 } 6553 } 6554 6555 /** 6556 * Used during creation of InstallArgs 6557 * 6558 * @param flags package installation flags 6559 * @return true if should be installed on external storage 6560 */ 6561 private static boolean installOnSd(int flags) { 6562 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 6563 return false; 6564 } 6565 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 6566 return true; 6567 } 6568 return false; 6569 } 6570 6571 /** 6572 * Used during creation of InstallArgs 6573 * 6574 * @param flags package installation flags 6575 * @return true if should be installed as forward locked 6576 */ 6577 private static boolean installForwardLocked(int flags) { 6578 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6579 } 6580 6581 private InstallArgs createInstallArgs(InstallParams params) { 6582 if (installOnSd(params.flags) || params.isForwardLocked()) { 6583 return new AsecInstallArgs(params); 6584 } else { 6585 return new FileInstallArgs(params); 6586 } 6587 } 6588 6589 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 6590 String nativeLibraryPath) { 6591 final boolean isInAsec; 6592 if (installOnSd(flags)) { 6593 /* Apps on SD card are always in ASEC containers. */ 6594 isInAsec = true; 6595 } else if (installForwardLocked(flags) 6596 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 6597 /* 6598 * Forward-locked apps are only in ASEC containers if they're the 6599 * new style 6600 */ 6601 isInAsec = true; 6602 } else { 6603 isInAsec = false; 6604 } 6605 6606 if (isInAsec) { 6607 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 6608 installOnSd(flags), installForwardLocked(flags)); 6609 } else { 6610 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath); 6611 } 6612 } 6613 6614 // Used by package mover 6615 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) { 6616 if (installOnSd(flags) || installForwardLocked(flags)) { 6617 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 6618 + AsecInstallArgs.RES_FILE_NAME); 6619 return new AsecInstallArgs(packageURI, cid, installOnSd(flags), 6620 installForwardLocked(flags)); 6621 } else { 6622 return new FileInstallArgs(packageURI, pkgName, dataDir); 6623 } 6624 } 6625 6626 static abstract class InstallArgs { 6627 final IPackageInstallObserver observer; 6628 // Always refers to PackageManager flags only 6629 final int flags; 6630 final Uri packageURI; 6631 final String installerPackageName; 6632 final ManifestDigest manifestDigest; 6633 final UserHandle user; 6634 6635 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags, 6636 String installerPackageName, ManifestDigest manifestDigest, 6637 UserHandle user) { 6638 this.packageURI = packageURI; 6639 this.flags = flags; 6640 this.observer = observer; 6641 this.installerPackageName = installerPackageName; 6642 this.manifestDigest = manifestDigest; 6643 this.user = user; 6644 } 6645 6646 abstract void createCopyFile(); 6647 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 6648 abstract int doPreInstall(int status); 6649 abstract boolean doRename(int status, String pkgName, String oldCodePath); 6650 6651 abstract int doPostInstall(int status, int uid); 6652 abstract String getCodePath(); 6653 abstract String getResourcePath(); 6654 abstract String getNativeLibraryPath(); 6655 // Need installer lock especially for dex file removal. 6656 abstract void cleanUpResourcesLI(); 6657 abstract boolean doPostDeleteLI(boolean delete); 6658 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 6659 6660 /** 6661 * Called before the source arguments are copied. This is used mostly 6662 * for MoveParams when it needs to read the source file to put it in the 6663 * destination. 6664 */ 6665 int doPreCopy() { 6666 return PackageManager.INSTALL_SUCCEEDED; 6667 } 6668 6669 /** 6670 * Called after the source arguments are copied. This is used mostly for 6671 * MoveParams when it needs to read the source file to put it in the 6672 * destination. 6673 * 6674 * @return 6675 */ 6676 int doPostCopy(int uid) { 6677 return PackageManager.INSTALL_SUCCEEDED; 6678 } 6679 6680 protected boolean isFwdLocked() { 6681 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6682 } 6683 } 6684 6685 class FileInstallArgs extends InstallArgs { 6686 File installDir; 6687 String codeFileName; 6688 String resourceFileName; 6689 String libraryPath; 6690 boolean created = false; 6691 6692 FileInstallArgs(InstallParams params) { 6693 super(params.getPackageUri(), params.observer, params.flags, 6694 params.installerPackageName, params.getManifestDigest(), 6695 params.getUser()); 6696 } 6697 6698 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) { 6699 super(null, null, 0, null, null, null); 6700 File codeFile = new File(fullCodePath); 6701 installDir = codeFile.getParentFile(); 6702 codeFileName = fullCodePath; 6703 resourceFileName = fullResourcePath; 6704 libraryPath = nativeLibraryPath; 6705 } 6706 6707 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) { 6708 super(packageURI, null, 0, null, null, null); 6709 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 6710 String apkName = getNextCodePath(null, pkgName, ".apk"); 6711 codeFileName = new File(installDir, apkName + ".apk").getPath(); 6712 resourceFileName = getResourcePathFromCodePath(); 6713 libraryPath = new File(dataDir, LIB_DIR_NAME).getPath(); 6714 } 6715 6716 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 6717 final long lowThreshold; 6718 6719 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 6720 .getService(DeviceStorageMonitorService.SERVICE); 6721 if (dsm == null) { 6722 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 6723 lowThreshold = 0L; 6724 } else { 6725 if (dsm.isMemoryLow()) { 6726 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 6727 return false; 6728 } 6729 6730 lowThreshold = dsm.getMemoryLowThreshold(); 6731 } 6732 6733 try { 6734 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6735 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6736 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 6737 } finally { 6738 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6739 } 6740 } 6741 6742 String getCodePath() { 6743 return codeFileName; 6744 } 6745 6746 void createCopyFile() { 6747 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 6748 codeFileName = createTempPackageFile(installDir).getPath(); 6749 resourceFileName = getResourcePathFromCodePath(); 6750 created = true; 6751 } 6752 6753 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 6754 if (temp) { 6755 // Generate temp file name 6756 createCopyFile(); 6757 } 6758 // Get a ParcelFileDescriptor to write to the output file 6759 File codeFile = new File(codeFileName); 6760 if (!created) { 6761 try { 6762 codeFile.createNewFile(); 6763 // Set permissions 6764 if (!setPermissions()) { 6765 // Failed setting permissions. 6766 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6767 } 6768 } catch (IOException e) { 6769 Slog.w(TAG, "Failed to create file " + codeFile); 6770 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6771 } 6772 } 6773 ParcelFileDescriptor out = null; 6774 try { 6775 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 6776 } catch (FileNotFoundException e) { 6777 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 6778 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6779 } 6780 // Copy the resource now 6781 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6782 try { 6783 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6784 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6785 ret = imcs.copyResource(packageURI, null, out); 6786 } finally { 6787 IoUtils.closeQuietly(out); 6788 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6789 } 6790 6791 if (isFwdLocked()) { 6792 final File destResourceFile = new File(getResourcePath()); 6793 6794 // Copy the public files 6795 try { 6796 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 6797 } catch (IOException e) { 6798 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 6799 + " forward-locked app."); 6800 destResourceFile.delete(); 6801 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6802 } 6803 } 6804 return ret; 6805 } 6806 6807 int doPreInstall(int status) { 6808 if (status != PackageManager.INSTALL_SUCCEEDED) { 6809 cleanUp(); 6810 } 6811 return status; 6812 } 6813 6814 boolean doRename(int status, final String pkgName, String oldCodePath) { 6815 if (status != PackageManager.INSTALL_SUCCEEDED) { 6816 cleanUp(); 6817 return false; 6818 } else { 6819 final File oldCodeFile = new File(getCodePath()); 6820 final File oldResourceFile = new File(getResourcePath()); 6821 6822 // Rename APK file based on packageName 6823 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 6824 final File newCodeFile = new File(installDir, apkName + ".apk"); 6825 if (!oldCodeFile.renameTo(newCodeFile)) { 6826 return false; 6827 } 6828 codeFileName = newCodeFile.getPath(); 6829 6830 // Rename public resource file if it's forward-locked. 6831 final File newResFile = new File(getResourcePathFromCodePath()); 6832 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 6833 return false; 6834 } 6835 resourceFileName = getResourcePathFromCodePath(); 6836 6837 // Attempt to set permissions 6838 if (!setPermissions()) { 6839 return false; 6840 } 6841 6842 if (!SELinux.restorecon(newCodeFile)) { 6843 return false; 6844 } 6845 6846 return true; 6847 } 6848 } 6849 6850 int doPostInstall(int status, int uid) { 6851 if (status != PackageManager.INSTALL_SUCCEEDED) { 6852 cleanUp(); 6853 } 6854 return status; 6855 } 6856 6857 String getResourcePath() { 6858 return resourceFileName; 6859 } 6860 6861 private String getResourcePathFromCodePath() { 6862 final String codePath = getCodePath(); 6863 if (isFwdLocked()) { 6864 final StringBuilder sb = new StringBuilder(); 6865 6866 sb.append(mAppInstallDir.getPath()); 6867 sb.append('/'); 6868 sb.append(getApkName(codePath)); 6869 sb.append(".zip"); 6870 6871 /* 6872 * If our APK is a temporary file, mark the resource as a 6873 * temporary file as well so it can be cleaned up after 6874 * catastrophic failure. 6875 */ 6876 if (codePath.endsWith(".tmp")) { 6877 sb.append(".tmp"); 6878 } 6879 6880 return sb.toString(); 6881 } else { 6882 return codePath; 6883 } 6884 } 6885 6886 @Override 6887 String getNativeLibraryPath() { 6888 return libraryPath; 6889 } 6890 6891 private boolean cleanUp() { 6892 boolean ret = true; 6893 String sourceDir = getCodePath(); 6894 String publicSourceDir = getResourcePath(); 6895 if (sourceDir != null) { 6896 File sourceFile = new File(sourceDir); 6897 if (!sourceFile.exists()) { 6898 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 6899 ret = false; 6900 } 6901 // Delete application's code and resources 6902 sourceFile.delete(); 6903 } 6904 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 6905 final File publicSourceFile = new File(publicSourceDir); 6906 if (!publicSourceFile.exists()) { 6907 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 6908 } 6909 if (publicSourceFile.exists()) { 6910 publicSourceFile.delete(); 6911 } 6912 } 6913 return ret; 6914 } 6915 6916 void cleanUpResourcesLI() { 6917 String sourceDir = getCodePath(); 6918 if (cleanUp()) { 6919 int retCode = mInstaller.rmdex(sourceDir); 6920 if (retCode < 0) { 6921 Slog.w(TAG, "Couldn't remove dex file for package: " 6922 + " at location " 6923 + sourceDir + ", retcode=" + retCode); 6924 // we don't consider this to be a failure of the core package deletion 6925 } 6926 } 6927 } 6928 6929 private boolean setPermissions() { 6930 // TODO Do this in a more elegant way later on. for now just a hack 6931 if (!isFwdLocked()) { 6932 final int filePermissions = 6933 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 6934 |FileUtils.S_IROTH; 6935 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 6936 if (retCode != 0) { 6937 Slog.e(TAG, "Couldn't set new package file permissions for " + 6938 getCodePath() 6939 + ". The return code was: " + retCode); 6940 // TODO Define new internal error 6941 return false; 6942 } 6943 return true; 6944 } 6945 return true; 6946 } 6947 6948 boolean doPostDeleteLI(boolean delete) { 6949 // XXX err, shouldn't we respect the delete flag? 6950 cleanUpResourcesLI(); 6951 return true; 6952 } 6953 } 6954 6955 private boolean isAsecExternal(String cid) { 6956 final String asecPath = PackageHelper.getSdFilesystem(cid); 6957 return !asecPath.startsWith(mAsecInternalPath); 6958 } 6959 6960 /** 6961 * Extract the MountService "container ID" from the full code path of an 6962 * .apk. 6963 */ 6964 static String cidFromCodePath(String fullCodePath) { 6965 int eidx = fullCodePath.lastIndexOf("/"); 6966 String subStr1 = fullCodePath.substring(0, eidx); 6967 int sidx = subStr1.lastIndexOf("/"); 6968 return subStr1.substring(sidx+1, eidx); 6969 } 6970 6971 class AsecInstallArgs extends InstallArgs { 6972 static final String RES_FILE_NAME = "pkg.apk"; 6973 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 6974 6975 String cid; 6976 String packagePath; 6977 String resourcePath; 6978 String libraryPath; 6979 6980 AsecInstallArgs(InstallParams params) { 6981 super(params.getPackageUri(), params.observer, params.flags, 6982 params.installerPackageName, params.getManifestDigest(), 6983 params.getUser()); 6984 } 6985 6986 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 6987 boolean isExternal, boolean isForwardLocked) { 6988 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 6989 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 6990 null, null, null); 6991 // Extract cid from fullCodePath 6992 int eidx = fullCodePath.lastIndexOf("/"); 6993 String subStr1 = fullCodePath.substring(0, eidx); 6994 int sidx = subStr1.lastIndexOf("/"); 6995 cid = subStr1.substring(sidx+1, eidx); 6996 setCachePath(subStr1); 6997 } 6998 6999 AsecInstallArgs(String cid, boolean isForwardLocked) { 7000 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 7001 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 7002 null, null, null); 7003 this.cid = cid; 7004 setCachePath(PackageHelper.getSdDir(cid)); 7005 } 7006 7007 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) { 7008 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 7009 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 7010 null, null, null); 7011 this.cid = cid; 7012 } 7013 7014 void createCopyFile() { 7015 cid = getTempContainerId(); 7016 } 7017 7018 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 7019 try { 7020 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 7021 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7022 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 7023 } finally { 7024 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 7025 } 7026 } 7027 7028 private final boolean isExternal() { 7029 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 7030 } 7031 7032 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 7033 if (temp) { 7034 createCopyFile(); 7035 } else { 7036 /* 7037 * Pre-emptively destroy the container since it's destroyed if 7038 * copying fails due to it existing anyway. 7039 */ 7040 PackageHelper.destroySdDir(cid); 7041 } 7042 7043 final String newCachePath; 7044 try { 7045 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 7046 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7047 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 7048 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 7049 } finally { 7050 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 7051 } 7052 7053 if (newCachePath != null) { 7054 setCachePath(newCachePath); 7055 return PackageManager.INSTALL_SUCCEEDED; 7056 } else { 7057 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7058 } 7059 } 7060 7061 @Override 7062 String getCodePath() { 7063 return packagePath; 7064 } 7065 7066 @Override 7067 String getResourcePath() { 7068 return resourcePath; 7069 } 7070 7071 @Override 7072 String getNativeLibraryPath() { 7073 return libraryPath; 7074 } 7075 7076 int doPreInstall(int status) { 7077 if (status != PackageManager.INSTALL_SUCCEEDED) { 7078 // Destroy container 7079 PackageHelper.destroySdDir(cid); 7080 } else { 7081 boolean mounted = PackageHelper.isContainerMounted(cid); 7082 if (!mounted) { 7083 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 7084 Process.SYSTEM_UID); 7085 if (newCachePath != null) { 7086 setCachePath(newCachePath); 7087 } else { 7088 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7089 } 7090 } 7091 } 7092 return status; 7093 } 7094 7095 boolean doRename(int status, final String pkgName, 7096 String oldCodePath) { 7097 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 7098 String newCachePath = null; 7099 if (PackageHelper.isContainerMounted(cid)) { 7100 // Unmount the container 7101 if (!PackageHelper.unMountSdDir(cid)) { 7102 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 7103 return false; 7104 } 7105 } 7106 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 7107 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 7108 " which might be stale. Will try to clean up."); 7109 // Clean up the stale container and proceed to recreate. 7110 if (!PackageHelper.destroySdDir(newCacheId)) { 7111 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 7112 return false; 7113 } 7114 // Successfully cleaned up stale container. Try to rename again. 7115 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 7116 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 7117 + " inspite of cleaning it up."); 7118 return false; 7119 } 7120 } 7121 if (!PackageHelper.isContainerMounted(newCacheId)) { 7122 Slog.w(TAG, "Mounting container " + newCacheId); 7123 newCachePath = PackageHelper.mountSdDir(newCacheId, 7124 getEncryptKey(), Process.SYSTEM_UID); 7125 } else { 7126 newCachePath = PackageHelper.getSdDir(newCacheId); 7127 } 7128 if (newCachePath == null) { 7129 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 7130 return false; 7131 } 7132 Log.i(TAG, "Succesfully renamed " + cid + 7133 " to " + newCacheId + 7134 " at new path: " + newCachePath); 7135 cid = newCacheId; 7136 setCachePath(newCachePath); 7137 return true; 7138 } 7139 7140 private void setCachePath(String newCachePath) { 7141 File cachePath = new File(newCachePath); 7142 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 7143 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 7144 7145 if (isFwdLocked()) { 7146 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 7147 } else { 7148 resourcePath = packagePath; 7149 } 7150 } 7151 7152 int doPostInstall(int status, int uid) { 7153 if (status != PackageManager.INSTALL_SUCCEEDED) { 7154 cleanUp(); 7155 } else { 7156 final int groupOwner; 7157 final String protectedFile; 7158 if (isFwdLocked()) { 7159 groupOwner = uid; 7160 protectedFile = RES_FILE_NAME; 7161 } else { 7162 groupOwner = -1; 7163 protectedFile = null; 7164 } 7165 7166 if (uid < Process.FIRST_APPLICATION_UID 7167 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 7168 Slog.e(TAG, "Failed to finalize " + cid); 7169 PackageHelper.destroySdDir(cid); 7170 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7171 } 7172 7173 boolean mounted = PackageHelper.isContainerMounted(cid); 7174 if (!mounted) { 7175 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 7176 } 7177 } 7178 return status; 7179 } 7180 7181 private void cleanUp() { 7182 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 7183 7184 // Destroy secure container 7185 PackageHelper.destroySdDir(cid); 7186 } 7187 7188 void cleanUpResourcesLI() { 7189 String sourceFile = getCodePath(); 7190 // Remove dex file 7191 int retCode = mInstaller.rmdex(sourceFile); 7192 if (retCode < 0) { 7193 Slog.w(TAG, "Couldn't remove dex file for package: " 7194 + " at location " 7195 + sourceFile.toString() + ", retcode=" + retCode); 7196 // we don't consider this to be a failure of the core package deletion 7197 } 7198 cleanUp(); 7199 } 7200 7201 boolean matchContainer(String app) { 7202 if (cid.startsWith(app)) { 7203 return true; 7204 } 7205 return false; 7206 } 7207 7208 String getPackageName() { 7209 return getAsecPackageName(cid); 7210 } 7211 7212 boolean doPostDeleteLI(boolean delete) { 7213 boolean ret = false; 7214 boolean mounted = PackageHelper.isContainerMounted(cid); 7215 if (mounted) { 7216 // Unmount first 7217 ret = PackageHelper.unMountSdDir(cid); 7218 } 7219 if (ret && delete) { 7220 cleanUpResourcesLI(); 7221 } 7222 return ret; 7223 } 7224 7225 @Override 7226 int doPreCopy() { 7227 if (isFwdLocked()) { 7228 if (!PackageHelper.fixSdPermissions(cid, 7229 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 7230 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7231 } 7232 } 7233 7234 return PackageManager.INSTALL_SUCCEEDED; 7235 } 7236 7237 @Override 7238 int doPostCopy(int uid) { 7239 if (isFwdLocked()) { 7240 if (uid < Process.FIRST_APPLICATION_UID 7241 || !PackageHelper.fixSdPermissions(cid, uid, RES_FILE_NAME)) { 7242 Slog.e(TAG, "Failed to finalize " + cid); 7243 PackageHelper.destroySdDir(cid); 7244 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7245 } 7246 } 7247 7248 return PackageManager.INSTALL_SUCCEEDED; 7249 } 7250 }; 7251 7252 static String getAsecPackageName(String packageCid) { 7253 int idx = packageCid.lastIndexOf("-"); 7254 if (idx == -1) { 7255 return packageCid; 7256 } 7257 return packageCid.substring(0, idx); 7258 } 7259 7260 // Utility method used to create code paths based on package name and available index. 7261 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 7262 String idxStr = ""; 7263 int idx = 1; 7264 // Fall back to default value of idx=1 if prefix is not 7265 // part of oldCodePath 7266 if (oldCodePath != null) { 7267 String subStr = oldCodePath; 7268 // Drop the suffix right away 7269 if (subStr.endsWith(suffix)) { 7270 subStr = subStr.substring(0, subStr.length() - suffix.length()); 7271 } 7272 // If oldCodePath already contains prefix find out the 7273 // ending index to either increment or decrement. 7274 int sidx = subStr.lastIndexOf(prefix); 7275 if (sidx != -1) { 7276 subStr = subStr.substring(sidx + prefix.length()); 7277 if (subStr != null) { 7278 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 7279 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 7280 } 7281 try { 7282 idx = Integer.parseInt(subStr); 7283 if (idx <= 1) { 7284 idx++; 7285 } else { 7286 idx--; 7287 } 7288 } catch(NumberFormatException e) { 7289 } 7290 } 7291 } 7292 } 7293 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 7294 return prefix + idxStr; 7295 } 7296 7297 // Utility method used to ignore ADD/REMOVE events 7298 // by directory observer. 7299 private static boolean ignoreCodePath(String fullPathStr) { 7300 String apkName = getApkName(fullPathStr); 7301 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 7302 if (idx != -1 && ((idx+1) < apkName.length())) { 7303 // Make sure the package ends with a numeral 7304 String version = apkName.substring(idx+1); 7305 try { 7306 Integer.parseInt(version); 7307 return true; 7308 } catch (NumberFormatException e) {} 7309 } 7310 return false; 7311 } 7312 7313 // Utility method that returns the relative package path with respect 7314 // to the installation directory. Like say for /data/data/com.test-1.apk 7315 // string com.test-1 is returned. 7316 static String getApkName(String codePath) { 7317 if (codePath == null) { 7318 return null; 7319 } 7320 int sidx = codePath.lastIndexOf("/"); 7321 int eidx = codePath.lastIndexOf("."); 7322 if (eidx == -1) { 7323 eidx = codePath.length(); 7324 } else if (eidx == 0) { 7325 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 7326 return null; 7327 } 7328 return codePath.substring(sidx+1, eidx); 7329 } 7330 7331 class PackageInstalledInfo { 7332 String name; 7333 int uid; 7334 // The set of users that originally had this package installed. 7335 int[] origUsers; 7336 // The set of users that now have this package installed. 7337 int[] newUsers; 7338 PackageParser.Package pkg; 7339 int returnCode; 7340 PackageRemovedInfo removedInfo; 7341 } 7342 7343 /* 7344 * Install a non-existing package. 7345 */ 7346 private void installNewPackageLI(PackageParser.Package pkg, 7347 int parseFlags, int scanMode, UserHandle user, 7348 String installerPackageName, PackageInstalledInfo res) { 7349 // Remember this for later, in case we need to rollback this install 7350 String pkgName = pkg.packageName; 7351 7352 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 7353 synchronized(mPackages) { 7354 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 7355 // A package with the same name is already installed, though 7356 // it has been renamed to an older name. The package we 7357 // are trying to install should be installed as an update to 7358 // the existing one, but that has not been requested, so bail. 7359 Slog.w(TAG, "Attempt to re-install " + pkgName 7360 + " without first uninstalling package running as " 7361 + mSettings.mRenamedPackages.get(pkgName)); 7362 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7363 return; 7364 } 7365 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 7366 // Don't allow installation over an existing package with the same name. 7367 Slog.w(TAG, "Attempt to re-install " + pkgName 7368 + " without first uninstalling."); 7369 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7370 return; 7371 } 7372 } 7373 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7374 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 7375 System.currentTimeMillis(), user); 7376 if (newPackage == null) { 7377 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7378 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7379 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7380 } 7381 } else { 7382 updateSettingsLI(newPackage, 7383 installerPackageName, 7384 res); 7385 // delete the partially installed application. the data directory will have to be 7386 // restored if it was already existing 7387 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7388 // remove package from internal structures. Note that we want deletePackageX to 7389 // delete the package data and cache directories that it created in 7390 // scanPackageLocked, unless those directories existed before we even tried to 7391 // install. 7392 deletePackageLI(pkgName, UserHandle.ALL, false, 7393 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 7394 res.removedInfo, true); 7395 } 7396 } 7397 } 7398 7399 private void replacePackageLI(PackageParser.Package pkg, 7400 int parseFlags, int scanMode, UserHandle user, 7401 String installerPackageName, PackageInstalledInfo res) { 7402 7403 PackageParser.Package oldPackage; 7404 String pkgName = pkg.packageName; 7405 // First find the old package info and check signatures 7406 synchronized(mPackages) { 7407 oldPackage = mPackages.get(pkgName); 7408 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 7409 != PackageManager.SIGNATURE_MATCH) { 7410 Slog.w(TAG, "New package has a different signature: " + pkgName); 7411 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 7412 return; 7413 } 7414 } 7415 boolean sysPkg = (isSystemApp(oldPackage)); 7416 if (sysPkg) { 7417 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 7418 user, installerPackageName, res); 7419 } else { 7420 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 7421 user, installerPackageName, res); 7422 } 7423 } 7424 7425 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 7426 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 7427 String installerPackageName, PackageInstalledInfo res) { 7428 PackageParser.Package newPackage = null; 7429 String pkgName = deletedPackage.packageName; 7430 boolean deletedPkg = true; 7431 boolean updatedSettings = false; 7432 7433 long origUpdateTime; 7434 if (pkg.mExtras != null) { 7435 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 7436 } else { 7437 origUpdateTime = 0; 7438 } 7439 7440 // First delete the existing package while retaining the data directory 7441 if (!deletePackageLI(pkgName, null, true, PackageManager.DELETE_KEEP_DATA, 7442 res.removedInfo, true)) { 7443 // If the existing package wasn't successfully deleted 7444 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 7445 deletedPkg = false; 7446 } else { 7447 // Successfully deleted the old package. Now proceed with re-installation 7448 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7449 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 7450 System.currentTimeMillis(), user); 7451 if (newPackage == null) { 7452 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7453 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7454 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7455 } 7456 } else { 7457 updateSettingsLI(newPackage, 7458 installerPackageName, 7459 res); 7460 updatedSettings = true; 7461 } 7462 } 7463 7464 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7465 // remove package from internal structures. Note that we want deletePackageX to 7466 // delete the package data and cache directories that it created in 7467 // scanPackageLocked, unless those directories existed before we even tried to 7468 // install. 7469 if(updatedSettings) { 7470 deletePackageLI( 7471 pkgName, null, true, 7472 PackageManager.DELETE_KEEP_DATA, 7473 res.removedInfo, true); 7474 } 7475 // Since we failed to install the new package we need to restore the old 7476 // package that we deleted. 7477 if(deletedPkg) { 7478 File restoreFile = new File(deletedPackage.mPath); 7479 // Parse old package 7480 boolean oldOnSd = isExternal(deletedPackage); 7481 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 7482 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 7483 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 7484 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 7485 | SCAN_UPDATE_TIME; 7486 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 7487 origUpdateTime, null) == null) { 7488 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 7489 return; 7490 } 7491 // Restore of old package succeeded. Update permissions. 7492 // writer 7493 synchronized (mPackages) { 7494 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 7495 UPDATE_PERMISSIONS_ALL); 7496 // can downgrade to reader 7497 mSettings.writeLPr(); 7498 } 7499 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 7500 } 7501 } 7502 } 7503 7504 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 7505 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 7506 String installerPackageName, PackageInstalledInfo res) { 7507 PackageParser.Package newPackage = null; 7508 boolean updatedSettings = false; 7509 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 7510 PackageParser.PARSE_IS_SYSTEM; 7511 String packageName = deletedPackage.packageName; 7512 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 7513 if (packageName == null) { 7514 Slog.w(TAG, "Attempt to delete null packageName."); 7515 return; 7516 } 7517 PackageParser.Package oldPkg; 7518 PackageSetting oldPkgSetting; 7519 // reader 7520 synchronized (mPackages) { 7521 oldPkg = mPackages.get(packageName); 7522 oldPkgSetting = mSettings.mPackages.get(packageName); 7523 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 7524 (oldPkgSetting == null)) { 7525 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 7526 return; 7527 } 7528 } 7529 7530 killApplication(packageName, oldPkg.applicationInfo.uid); 7531 7532 res.removedInfo.uid = oldPkg.applicationInfo.uid; 7533 res.removedInfo.removedPackage = packageName; 7534 // Remove existing system package 7535 removePackageLI(oldPkg, true); 7536 // writer 7537 synchronized (mPackages) { 7538 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 7539 // We didn't need to disable the .apk as a current system package, 7540 // which means we are replacing another update that is already 7541 // installed. We need to make sure to delete the older one's .apk. 7542 res.removedInfo.args = createInstallArgs(0, 7543 deletedPackage.applicationInfo.sourceDir, 7544 deletedPackage.applicationInfo.publicSourceDir, 7545 deletedPackage.applicationInfo.nativeLibraryDir); 7546 } else { 7547 res.removedInfo.args = null; 7548 } 7549 } 7550 7551 // Successfully disabled the old package. Now proceed with re-installation 7552 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7553 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7554 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 7555 if (newPackage == null) { 7556 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7557 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7558 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7559 } 7560 } else { 7561 if (newPackage.mExtras != null) { 7562 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 7563 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 7564 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 7565 } 7566 updateSettingsLI(newPackage, installerPackageName, res); 7567 updatedSettings = true; 7568 } 7569 7570 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7571 // Re installation failed. Restore old information 7572 // Remove new pkg information 7573 if (newPackage != null) { 7574 removePackageLI(newPackage, true); 7575 } 7576 // Add back the old system package 7577 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 7578 // Restore the old system information in Settings 7579 synchronized(mPackages) { 7580 if (updatedSettings) { 7581 mSettings.enableSystemPackageLPw(packageName); 7582 mSettings.setInstallerPackageName(packageName, 7583 oldPkgSetting.installerPackageName); 7584 } 7585 mSettings.writeLPr(); 7586 } 7587 } 7588 } 7589 7590 // Utility method used to move dex files during install. 7591 private int moveDexFilesLI(PackageParser.Package newPackage) { 7592 int retCode; 7593 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 7594 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath); 7595 if (retCode != 0) { 7596 if (mNoDexOpt) { 7597 /* 7598 * If we're in an engineering build, programs are lazily run 7599 * through dexopt. If the .dex file doesn't exist yet, it 7600 * will be created when the program is run next. 7601 */ 7602 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 7603 } else { 7604 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 7605 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7606 } 7607 } 7608 } 7609 return PackageManager.INSTALL_SUCCEEDED; 7610 } 7611 7612 private void updateSettingsLI(PackageParser.Package newPackage, 7613 String installerPackageName, PackageInstalledInfo res) { 7614 String pkgName = newPackage.packageName; 7615 synchronized (mPackages) { 7616 //write settings. the installStatus will be incomplete at this stage. 7617 //note that the new package setting would have already been 7618 //added to mPackages. It hasn't been persisted yet. 7619 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 7620 mSettings.writeLPr(); 7621 } 7622 7623 if ((res.returnCode = moveDexFilesLI(newPackage)) 7624 != PackageManager.INSTALL_SUCCEEDED) { 7625 // Discontinue if moving dex files failed. 7626 return; 7627 } 7628 7629 Log.d(TAG, "New package installed in " + newPackage.mPath); 7630 7631 synchronized (mPackages) { 7632 updatePermissionsLPw(newPackage.packageName, newPackage, 7633 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 7634 ? UPDATE_PERMISSIONS_ALL : 0)); 7635 res.name = pkgName; 7636 res.uid = newPackage.applicationInfo.uid; 7637 res.pkg = newPackage; 7638 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 7639 mSettings.setInstallerPackageName(pkgName, installerPackageName); 7640 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 7641 //to update install status 7642 mSettings.writeLPr(); 7643 } 7644 } 7645 7646 private void installPackageLI(InstallArgs args, 7647 boolean newInstall, PackageInstalledInfo res) { 7648 int pFlags = args.flags; 7649 String installerPackageName = args.installerPackageName; 7650 File tmpPackageFile = new File(args.getCodePath()); 7651 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 7652 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 7653 boolean replace = false; 7654 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 7655 | (newInstall ? SCAN_NEW_INSTALL : 0); 7656 // Result object to be returned 7657 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 7658 7659 // Retrieve PackageSettings and parse package 7660 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 7661 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 7662 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 7663 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 7664 pp.setSeparateProcesses(mSeparateProcesses); 7665 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 7666 null, mMetrics, parseFlags); 7667 if (pkg == null) { 7668 res.returnCode = pp.getParseError(); 7669 return; 7670 } 7671 String pkgName = res.name = pkg.packageName; 7672 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 7673 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 7674 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 7675 return; 7676 } 7677 } 7678 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) { 7679 res.returnCode = pp.getParseError(); 7680 return; 7681 } 7682 7683 /* If the installer passed in a manifest digest, compare it now. */ 7684 if (args.manifestDigest != null) { 7685 if (DEBUG_INSTALL) { 7686 final String parsedManifest = pkg.manifestDigest == null ? "null" 7687 : pkg.manifestDigest.toString(); 7688 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 7689 + parsedManifest); 7690 } 7691 7692 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 7693 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 7694 return; 7695 } 7696 } else if (DEBUG_INSTALL) { 7697 final String parsedManifest = pkg.manifestDigest == null 7698 ? "null" : pkg.manifestDigest.toString(); 7699 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 7700 } 7701 7702 // Get rid of all references to package scan path via parser. 7703 pp = null; 7704 String oldCodePath = null; 7705 boolean systemApp = false; 7706 synchronized (mPackages) { 7707 // Check if installing already existing package 7708 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 7709 String oldName = mSettings.mRenamedPackages.get(pkgName); 7710 if (pkg.mOriginalPackages != null 7711 && pkg.mOriginalPackages.contains(oldName) 7712 && mPackages.containsKey(oldName)) { 7713 // This package is derived from an original package, 7714 // and this device has been updating from that original 7715 // name. We must continue using the original name, so 7716 // rename the new package here. 7717 pkg.setPackageName(oldName); 7718 pkgName = pkg.packageName; 7719 replace = true; 7720 } else if (mPackages.containsKey(pkgName)) { 7721 // This package, under its official name, already exists 7722 // on the device; we should replace it. 7723 replace = true; 7724 } 7725 } 7726 PackageSetting ps = mSettings.mPackages.get(pkgName); 7727 if (ps != null) { 7728 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 7729 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7730 systemApp = (ps.pkg.applicationInfo.flags & 7731 ApplicationInfo.FLAG_SYSTEM) != 0; 7732 } 7733 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7734 } 7735 } 7736 7737 if (systemApp && onSd) { 7738 // Disable updates to system apps on sdcard 7739 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 7740 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 7741 return; 7742 } 7743 7744 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 7745 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7746 return; 7747 } 7748 // Set application objects path explicitly after the rename 7749 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 7750 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 7751 if (replace) { 7752 replacePackageLI(pkg, parseFlags, scanMode, args.user, 7753 installerPackageName, res); 7754 } else { 7755 installNewPackageLI(pkg, parseFlags, scanMode, args.user, 7756 installerPackageName, res); 7757 } 7758 synchronized (mPackages) { 7759 final PackageSetting ps = mSettings.mPackages.get(pkgName); 7760 if (ps != null) { 7761 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7762 } 7763 } 7764 } 7765 7766 private static boolean isForwardLocked(PackageParser.Package pkg) { 7767 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 7768 } 7769 7770 7771 private boolean isForwardLocked(PackageSetting ps) { 7772 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 7773 } 7774 7775 private static boolean isExternal(PackageParser.Package pkg) { 7776 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 7777 } 7778 7779 private static boolean isExternal(PackageSetting ps) { 7780 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 7781 } 7782 7783 private static boolean isSystemApp(PackageParser.Package pkg) { 7784 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7785 } 7786 7787 private static boolean isSystemApp(ApplicationInfo info) { 7788 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7789 } 7790 7791 private static boolean isSystemApp(PackageSetting ps) { 7792 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 7793 } 7794 7795 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 7796 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 7797 } 7798 7799 private int packageFlagsToInstallFlags(PackageSetting ps) { 7800 int installFlags = 0; 7801 if (isExternal(ps)) { 7802 installFlags |= PackageManager.INSTALL_EXTERNAL; 7803 } 7804 if (isForwardLocked(ps)) { 7805 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 7806 } 7807 return installFlags; 7808 } 7809 7810 private void deleteTempPackageFiles() { 7811 FilenameFilter filter = new FilenameFilter() { 7812 public boolean accept(File dir, String name) { 7813 return name.startsWith("vmdl") && name.endsWith(".tmp"); 7814 } 7815 }; 7816 String tmpFilesList[] = mAppInstallDir.list(filter); 7817 if(tmpFilesList == null) { 7818 return; 7819 } 7820 for(int i = 0; i < tmpFilesList.length; i++) { 7821 File tmpFile = new File(mAppInstallDir, tmpFilesList[i]); 7822 tmpFile.delete(); 7823 } 7824 } 7825 7826 private File createTempPackageFile(File installDir) { 7827 File tmpPackageFile; 7828 try { 7829 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 7830 } catch (IOException e) { 7831 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 7832 return null; 7833 } 7834 try { 7835 FileUtils.setPermissions( 7836 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 7837 -1, -1); 7838 if (!SELinux.restorecon(tmpPackageFile)) { 7839 return null; 7840 } 7841 } catch (IOException e) { 7842 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 7843 return null; 7844 } 7845 return tmpPackageFile; 7846 } 7847 7848 public void deletePackage(final String packageName, 7849 final IPackageDeleteObserver observer, 7850 final int flags) { 7851 mContext.enforceCallingOrSelfPermission( 7852 android.Manifest.permission.DELETE_PACKAGES, null); 7853 // Queue up an async operation since the package deletion may take a little while. 7854 final int uid = Binder.getCallingUid(); 7855 mHandler.post(new Runnable() { 7856 public void run() { 7857 mHandler.removeCallbacks(this); 7858 final int returnCode = deletePackageX(packageName, uid, flags); 7859 if (observer != null) { 7860 try { 7861 observer.packageDeleted(packageName, returnCode); 7862 } catch (RemoteException e) { 7863 Log.i(TAG, "Observer no longer exists."); 7864 } //end catch 7865 } //end if 7866 } //end run 7867 }); 7868 } 7869 7870 /** 7871 * This method is an internal method that could be get invoked either 7872 * to delete an installed package or to clean up a failed installation. 7873 * After deleting an installed package, a broadcast is sent to notify any 7874 * listeners that the package has been installed. For cleaning up a failed 7875 * installation, the broadcast is not necessary since the package's 7876 * installation wouldn't have sent the initial broadcast either 7877 * The key steps in deleting a package are 7878 * deleting the package information in internal structures like mPackages, 7879 * deleting the packages base directories through installd 7880 * updating mSettings to reflect current status 7881 * persisting settings for later use 7882 * sending a broadcast if necessary 7883 */ 7884 private int deletePackageX(String packageName, int uid, int flags) { 7885 final PackageRemovedInfo info = new PackageRemovedInfo(); 7886 final boolean res; 7887 7888 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 7889 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 7890 try { 7891 if (dpm != null && dpm.packageHasActiveAdmins(packageName)) { 7892 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 7893 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 7894 } 7895 } catch (RemoteException e) { 7896 } 7897 7898 synchronized (mInstallLock) { 7899 res = deletePackageLI(packageName, 7900 (flags & PackageManager.DELETE_ALL_USERS) != 0 7901 ? UserHandle.ALL : new UserHandle(UserHandle.getUserId(uid)), 7902 true, flags | REMOVE_CHATTY, info, true); 7903 } 7904 7905 if (res) { 7906 boolean systemUpdate = info.isRemovedPackageSystemUpdate; 7907 info.sendBroadcast(true, systemUpdate); 7908 7909 // If the removed package was a system update, the old system packaged 7910 // was re-enabled; we need to broadcast this information 7911 if (systemUpdate) { 7912 Bundle extras = new Bundle(1); 7913 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 7914 ? info.removedAppId : info.uid); 7915 extras.putBoolean(Intent.EXTRA_REPLACING, true); 7916 7917 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 7918 extras, null, null, null); 7919 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 7920 extras, null, null, null); 7921 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 7922 null, packageName, null, null); 7923 } 7924 } 7925 // Force a gc here. 7926 Runtime.getRuntime().gc(); 7927 // Delete the resources here after sending the broadcast to let 7928 // other processes clean up before deleting resources. 7929 if (info.args != null) { 7930 synchronized (mInstallLock) { 7931 info.args.doPostDeleteLI(true); 7932 } 7933 } 7934 7935 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 7936 } 7937 7938 static class PackageRemovedInfo { 7939 String removedPackage; 7940 int uid = -1; 7941 int removedAppId = -1; 7942 int[] removedUsers = null; 7943 boolean isRemovedPackageSystemUpdate = false; 7944 // Clean up resources deleted packages. 7945 InstallArgs args = null; 7946 7947 void sendBroadcast(boolean fullRemove, boolean replacing) { 7948 Bundle extras = new Bundle(1); 7949 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 7950 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 7951 if (replacing) { 7952 extras.putBoolean(Intent.EXTRA_REPLACING, true); 7953 } 7954 if (removedPackage != null) { 7955 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 7956 extras, null, null, removedUsers); 7957 if (fullRemove && !replacing) { 7958 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 7959 extras, null, null, removedUsers); 7960 } 7961 } 7962 if (removedAppId >= 0) { 7963 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 7964 removedUsers); 7965 } 7966 } 7967 } 7968 7969 /* 7970 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 7971 * flag is not set, the data directory is removed as well. 7972 * make sure this flag is set for partially installed apps. If not its meaningless to 7973 * delete a partially installed application. 7974 */ 7975 private void removePackageDataLI(PackageParser.Package p, PackageRemovedInfo outInfo, 7976 int flags, boolean writeSettings) { 7977 String packageName = p.packageName; 7978 removePackageLI(p, (flags&REMOVE_CHATTY) != 0); 7979 // Retrieve object to delete permissions for shared user later on 7980 final PackageSetting deletedPs; 7981 // reader 7982 synchronized (mPackages) { 7983 deletedPs = mSettings.mPackages.get(packageName); 7984 if (outInfo != null) { 7985 outInfo.removedPackage = packageName; 7986 outInfo.removedUsers = deletedPs != null 7987 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 7988 : null; 7989 } 7990 } 7991 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 7992 removeDataDirsLI(packageName); 7993 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 7994 } 7995 // writer 7996 synchronized (mPackages) { 7997 if (deletedPs != null) { 7998 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 7999 if (outInfo != null) { 8000 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 8001 } 8002 if (deletedPs != null) { 8003 updatePermissionsLPw(deletedPs.name, null, 0); 8004 if (deletedPs.sharedUser != null) { 8005 // remove permissions associated with package 8006 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 8007 } 8008 } 8009 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 8010 } 8011 } 8012 // can downgrade to reader 8013 if (writeSettings) { 8014 // Save settings now 8015 mSettings.writeLPr(); 8016 } 8017 } 8018 } 8019 8020 /* 8021 * Tries to delete system package. 8022 */ 8023 private boolean deleteSystemPackageLI(PackageParser.Package p, 8024 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 8025 ApplicationInfo applicationInfo = p.applicationInfo; 8026 //applicable for non-partially installed applications only 8027 if (applicationInfo == null) { 8028 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo."); 8029 return false; 8030 } 8031 PackageSetting ps = null; 8032 // Confirm if the system package has been updated 8033 // An updated system app can be deleted. This will also have to restore 8034 // the system pkg from system partition 8035 // reader 8036 synchronized (mPackages) { 8037 ps = mSettings.getDisabledSystemPkgLPr(p.packageName); 8038 } 8039 if (ps == null) { 8040 Slog.w(TAG, "Attempt to delete unknown system package "+ p.packageName); 8041 return false; 8042 } else { 8043 Log.i(TAG, "Deleting system pkg from data partition"); 8044 } 8045 // Delete the updated package 8046 outInfo.isRemovedPackageSystemUpdate = true; 8047 if (ps.versionCode < p.mVersionCode) { 8048 // Delete data for downgrades 8049 flags &= ~PackageManager.DELETE_KEEP_DATA; 8050 } else { 8051 // Preserve data by setting flag 8052 flags |= PackageManager.DELETE_KEEP_DATA; 8053 } 8054 boolean ret = deleteInstalledPackageLI(p, true, flags, outInfo, 8055 writeSettings); 8056 if (!ret) { 8057 return false; 8058 } 8059 // writer 8060 synchronized (mPackages) { 8061 // Reinstate the old system package 8062 mSettings.enableSystemPackageLPw(p.packageName); 8063 // Remove any native libraries from the upgraded package. 8064 NativeLibraryHelper.removeNativeBinariesLI(p.applicationInfo.nativeLibraryDir); 8065 } 8066 // Install the system package 8067 PackageParser.Package newPkg = scanPackageLI(ps.codePath, 8068 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM, 8069 SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 8070 8071 if (newPkg == null) { 8072 Slog.w(TAG, "Failed to restore system package:"+p.packageName+" with error:" + mLastScanError); 8073 return false; 8074 } 8075 // writer 8076 synchronized (mPackages) { 8077 updatePermissionsLPw(newPkg.packageName, newPkg, 8078 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 8079 // can downgrade to reader here 8080 if (writeSettings) { 8081 mSettings.writeLPr(); 8082 } 8083 } 8084 return true; 8085 } 8086 8087 private boolean deleteInstalledPackageLI(PackageParser.Package p, 8088 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo, 8089 boolean writeSettings) { 8090 ApplicationInfo applicationInfo = p.applicationInfo; 8091 if (applicationInfo == null) { 8092 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo."); 8093 return false; 8094 } 8095 if (outInfo != null) { 8096 outInfo.uid = applicationInfo.uid; 8097 } 8098 8099 // Delete package data from internal structures and also remove data if flag is set 8100 removePackageDataLI(p, outInfo, flags, writeSettings); 8101 8102 // Delete application code and resources 8103 if (deleteCodeAndResources) { 8104 // TODO can pick up from PackageSettings as well 8105 int installFlags = isExternal(p) ? PackageManager.INSTALL_EXTERNAL : 0; 8106 installFlags |= isForwardLocked(p) ? PackageManager.INSTALL_FORWARD_LOCK : 0; 8107 outInfo.args = createInstallArgs(installFlags, applicationInfo.sourceDir, 8108 applicationInfo.publicSourceDir, applicationInfo.nativeLibraryDir); 8109 } 8110 return true; 8111 } 8112 8113 /* 8114 * This method handles package deletion in general 8115 */ 8116 private boolean deletePackageLI(String packageName, UserHandle user, 8117 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo, 8118 boolean writeSettings) { 8119 if (packageName == null) { 8120 Slog.w(TAG, "Attempt to delete null packageName."); 8121 return false; 8122 } 8123 PackageParser.Package p; 8124 boolean dataOnly = false; 8125 int removeUser = -1; 8126 int appId = -1; 8127 synchronized (mPackages) { 8128 p = mPackages.get(packageName); 8129 if (p == null) { 8130 //this retrieves partially installed apps 8131 dataOnly = true; 8132 PackageSetting ps = mSettings.mPackages.get(packageName); 8133 if (ps == null) { 8134 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 8135 return false; 8136 } 8137 p = ps.pkg; 8138 } 8139 if (p == null) { 8140 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 8141 return false; 8142 } 8143 final PackageSetting ps = (PackageSetting)p.mExtras; 8144 if (!isSystemApp(p) && ps != null && user != null 8145 && user.getIdentifier() != UserHandle.USER_ALL) { 8146 // The caller is asking that the package only be deleted for a single 8147 // user. To do this, we just mark its uninstalled state and delete 8148 // its data. 8149 ps.setUserState(user.getIdentifier(), 8150 COMPONENT_ENABLED_STATE_DEFAULT, 8151 false, //installed 8152 true, //stopped 8153 true, //notLaunched 8154 null, null); 8155 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 8156 // Other user still have this package installed, so all 8157 // we need to do is clear this user's data and save that 8158 // it is uninstalled. 8159 removeUser = user.getIdentifier(); 8160 appId = ps.appId; 8161 mSettings.writePackageRestrictionsLPr(removeUser); 8162 } else { 8163 // We need to set it back to 'installed' so the uninstall 8164 // broadcasts will be sent correctly. 8165 ps.setInstalled(true, user.getIdentifier()); 8166 } 8167 } 8168 } 8169 8170 if (removeUser >= 0) { 8171 // From above, we determined that we are deleting this only 8172 // for a single user. Continue the work here. 8173 if (outInfo != null) { 8174 outInfo.removedPackage = packageName; 8175 outInfo.removedAppId = appId; 8176 outInfo.removedUsers = new int[] {removeUser}; 8177 } 8178 mInstaller.clearUserData(packageName, removeUser); 8179 schedulePackageCleaning(packageName, removeUser, false); 8180 return true; 8181 } 8182 8183 if (dataOnly) { 8184 // Delete application data first 8185 removePackageDataLI(p, outInfo, flags, writeSettings); 8186 return true; 8187 } 8188 // At this point the package should have ApplicationInfo associated with it 8189 if (p.applicationInfo == null) { 8190 Slog.w(TAG, "Package " + p.packageName + " has no applicationInfo."); 8191 return false; 8192 } 8193 boolean ret = false; 8194 if (isSystemApp(p)) { 8195 Log.i(TAG, "Removing system package:"+p.packageName); 8196 // When an updated system application is deleted we delete the existing resources as well and 8197 // fall back to existing code in system partition 8198 ret = deleteSystemPackageLI(p, flags, outInfo, writeSettings); 8199 } else { 8200 Log.i(TAG, "Removing non-system package:"+p.packageName); 8201 // Kill application pre-emptively especially for apps on sd. 8202 killApplication(packageName, p.applicationInfo.uid); 8203 ret = deleteInstalledPackageLI(p, deleteCodeAndResources, flags, outInfo, 8204 writeSettings); 8205 } 8206 return ret; 8207 } 8208 8209 private final class ClearStorageConnection implements ServiceConnection { 8210 IMediaContainerService mContainerService; 8211 8212 @Override 8213 public void onServiceConnected(ComponentName name, IBinder service) { 8214 synchronized (this) { 8215 mContainerService = IMediaContainerService.Stub.asInterface(service); 8216 notifyAll(); 8217 } 8218 } 8219 8220 @Override 8221 public void onServiceDisconnected(ComponentName name) { 8222 } 8223 } 8224 8225 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 8226 final boolean mounted; 8227 if (Environment.isExternalStorageEmulated()) { 8228 mounted = true; 8229 } else { 8230 final String status = Environment.getExternalStorageState(); 8231 8232 mounted = status.equals(Environment.MEDIA_MOUNTED) 8233 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 8234 } 8235 8236 if (!mounted) { 8237 return; 8238 } 8239 8240 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 8241 int[] users; 8242 if (userId == UserHandle.USER_ALL) { 8243 users = sUserManager.getUserIds(); 8244 } else { 8245 users = new int[] { userId }; 8246 } 8247 for (int curUser : users) { 8248 ClearStorageConnection conn = new ClearStorageConnection(); 8249 if (mContext.bindService(containerIntent, conn, Context.BIND_AUTO_CREATE, curUser)) { 8250 try { 8251 long timeout = SystemClock.uptimeMillis() + 5000; 8252 synchronized (conn) { 8253 long now = SystemClock.uptimeMillis(); 8254 while (conn.mContainerService == null && now < timeout) { 8255 try { 8256 conn.wait(timeout - now); 8257 } catch (InterruptedException e) { 8258 } 8259 } 8260 } 8261 if (conn.mContainerService == null) { 8262 return; 8263 } 8264 final File externalCacheDir = Environment 8265 .getExternalStorageAppCacheDirectory(packageName); 8266 try { 8267 conn.mContainerService.clearDirectory(externalCacheDir.toString()); 8268 } catch (RemoteException e) { 8269 } 8270 if (allData) { 8271 final File externalDataDir = Environment 8272 .getExternalStorageAppDataDirectory(packageName); 8273 try { 8274 conn.mContainerService.clearDirectory(externalDataDir.toString()); 8275 } catch (RemoteException e) { 8276 } 8277 final File externalMediaDir = Environment 8278 .getExternalStorageAppMediaDirectory(packageName); 8279 try { 8280 conn.mContainerService.clearDirectory(externalMediaDir.toString()); 8281 } catch (RemoteException e) { 8282 } 8283 } 8284 } finally { 8285 mContext.unbindService(conn); 8286 } 8287 } 8288 } 8289 } 8290 8291 @Override 8292 public void clearApplicationUserData(final String packageName, 8293 final IPackageDataObserver observer, final int userId) { 8294 mContext.enforceCallingOrSelfPermission( 8295 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 8296 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 8297 // Queue up an async operation since the package deletion may take a little while. 8298 mHandler.post(new Runnable() { 8299 public void run() { 8300 mHandler.removeCallbacks(this); 8301 final boolean succeeded; 8302 synchronized (mInstallLock) { 8303 succeeded = clearApplicationUserDataLI(packageName, userId); 8304 } 8305 clearExternalStorageDataSync(packageName, userId, true); 8306 if (succeeded) { 8307 // invoke DeviceStorageMonitor's update method to clear any notifications 8308 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) 8309 ServiceManager.getService(DeviceStorageMonitorService.SERVICE); 8310 if (dsm != null) { 8311 dsm.updateMemory(); 8312 } 8313 } 8314 if(observer != null) { 8315 try { 8316 observer.onRemoveCompleted(packageName, succeeded); 8317 } catch (RemoteException e) { 8318 Log.i(TAG, "Observer no longer exists."); 8319 } 8320 } //end if observer 8321 } //end run 8322 }); 8323 } 8324 8325 private boolean clearApplicationUserDataLI(String packageName, int userId) { 8326 if (packageName == null) { 8327 Slog.w(TAG, "Attempt to delete null packageName."); 8328 return false; 8329 } 8330 PackageParser.Package p; 8331 boolean dataOnly = false; 8332 synchronized (mPackages) { 8333 p = mPackages.get(packageName); 8334 if(p == null) { 8335 dataOnly = true; 8336 PackageSetting ps = mSettings.mPackages.get(packageName); 8337 if((ps == null) || (ps.pkg == null)) { 8338 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8339 return false; 8340 } 8341 p = ps.pkg; 8342 } 8343 } 8344 8345 if (!dataOnly) { 8346 //need to check this only for fully installed applications 8347 if (p == null) { 8348 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8349 return false; 8350 } 8351 final ApplicationInfo applicationInfo = p.applicationInfo; 8352 if (applicationInfo == null) { 8353 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8354 return false; 8355 } 8356 } 8357 int retCode = mInstaller.clearUserData(packageName, userId); 8358 if (retCode < 0) { 8359 Slog.w(TAG, "Couldn't remove cache files for package: " 8360 + packageName); 8361 return false; 8362 } 8363 return true; 8364 } 8365 8366 public void deleteApplicationCacheFiles(final String packageName, 8367 final IPackageDataObserver observer) { 8368 mContext.enforceCallingOrSelfPermission( 8369 android.Manifest.permission.DELETE_CACHE_FILES, null); 8370 // Queue up an async operation since the package deletion may take a little while. 8371 final int userId = UserHandle.getCallingUserId(); 8372 mHandler.post(new Runnable() { 8373 public void run() { 8374 mHandler.removeCallbacks(this); 8375 final boolean succeded; 8376 synchronized (mInstallLock) { 8377 succeded = deleteApplicationCacheFilesLI(packageName, userId); 8378 } 8379 clearExternalStorageDataSync(packageName, userId, false); 8380 if(observer != null) { 8381 try { 8382 observer.onRemoveCompleted(packageName, succeded); 8383 } catch (RemoteException e) { 8384 Log.i(TAG, "Observer no longer exists."); 8385 } 8386 } //end if observer 8387 } //end run 8388 }); 8389 } 8390 8391 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 8392 if (packageName == null) { 8393 Slog.w(TAG, "Attempt to delete null packageName."); 8394 return false; 8395 } 8396 PackageParser.Package p; 8397 synchronized (mPackages) { 8398 p = mPackages.get(packageName); 8399 } 8400 if (p == null) { 8401 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8402 return false; 8403 } 8404 final ApplicationInfo applicationInfo = p.applicationInfo; 8405 if (applicationInfo == null) { 8406 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8407 return false; 8408 } 8409 // TODO: Pass userId to deleteCacheFiles 8410 int retCode = mInstaller.deleteCacheFiles(packageName); 8411 if (retCode < 0) { 8412 Slog.w(TAG, "Couldn't remove cache files for package: " 8413 + packageName); 8414 return false; 8415 } 8416 return true; 8417 } 8418 8419 public void getPackageSizeInfo(final String packageName, int userHandle, 8420 final IPackageStatsObserver observer) { 8421 mContext.enforceCallingOrSelfPermission( 8422 android.Manifest.permission.GET_PACKAGE_SIZE, null); 8423 8424 PackageStats stats = new PackageStats(packageName, userHandle); 8425 8426 /* 8427 * Queue up an async operation since the package measurement may take a 8428 * little while. 8429 */ 8430 Message msg = mHandler.obtainMessage(INIT_COPY); 8431 msg.obj = new MeasureParams(stats, observer); 8432 mHandler.sendMessage(msg); 8433 } 8434 8435 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 8436 PackageStats pStats) { 8437 if (packageName == null) { 8438 Slog.w(TAG, "Attempt to get size of null packageName."); 8439 return false; 8440 } 8441 PackageParser.Package p; 8442 boolean dataOnly = false; 8443 String asecPath = null; 8444 synchronized (mPackages) { 8445 p = mPackages.get(packageName); 8446 if(p == null) { 8447 dataOnly = true; 8448 PackageSetting ps = mSettings.mPackages.get(packageName); 8449 if((ps == null) || (ps.pkg == null)) { 8450 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8451 return false; 8452 } 8453 p = ps.pkg; 8454 } 8455 if (p != null && (isExternal(p) || isForwardLocked(p))) { 8456 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 8457 if (secureContainerId != null) { 8458 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 8459 } 8460 } 8461 } 8462 String publicSrcDir = null; 8463 if(!dataOnly) { 8464 final ApplicationInfo applicationInfo = p.applicationInfo; 8465 if (applicationInfo == null) { 8466 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8467 return false; 8468 } 8469 if (isForwardLocked(p)) { 8470 publicSrcDir = applicationInfo.publicSourceDir; 8471 } 8472 } 8473 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, publicSrcDir, 8474 asecPath, pStats); 8475 if (res < 0) { 8476 return false; 8477 } 8478 8479 // Fix-up for forward-locked applications in ASEC containers. 8480 if (!isExternal(p)) { 8481 pStats.codeSize += pStats.externalCodeSize; 8482 pStats.externalCodeSize = 0L; 8483 } 8484 8485 return true; 8486 } 8487 8488 8489 public void addPackageToPreferred(String packageName) { 8490 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 8491 } 8492 8493 public void removePackageFromPreferred(String packageName) { 8494 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 8495 } 8496 8497 public List<PackageInfo> getPreferredPackages(int flags) { 8498 return new ArrayList<PackageInfo>(); 8499 } 8500 8501 private int getUidTargetSdkVersionLockedLPr(int uid) { 8502 Object obj = mSettings.getUserIdLPr(uid); 8503 if (obj instanceof SharedUserSetting) { 8504 final SharedUserSetting sus = (SharedUserSetting) obj; 8505 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 8506 final Iterator<PackageSetting> it = sus.packages.iterator(); 8507 while (it.hasNext()) { 8508 final PackageSetting ps = it.next(); 8509 if (ps.pkg != null) { 8510 int v = ps.pkg.applicationInfo.targetSdkVersion; 8511 if (v < vers) vers = v; 8512 } 8513 } 8514 return vers; 8515 } else if (obj instanceof PackageSetting) { 8516 final PackageSetting ps = (PackageSetting) obj; 8517 if (ps.pkg != null) { 8518 return ps.pkg.applicationInfo.targetSdkVersion; 8519 } 8520 } 8521 return Build.VERSION_CODES.CUR_DEVELOPMENT; 8522 } 8523 8524 public void addPreferredActivity(IntentFilter filter, int match, 8525 ComponentName[] set, ComponentName activity, int userId) { 8526 // writer 8527 int callingUid = Binder.getCallingUid(); 8528 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 8529 synchronized (mPackages) { 8530 if (mContext.checkCallingOrSelfPermission( 8531 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8532 != PackageManager.PERMISSION_GRANTED) { 8533 if (getUidTargetSdkVersionLockedLPr(callingUid) 8534 < Build.VERSION_CODES.FROYO) { 8535 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 8536 + callingUid); 8537 return; 8538 } 8539 mContext.enforceCallingOrSelfPermission( 8540 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8541 } 8542 8543 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 8544 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 8545 mSettings.mPreferredActivities.addFilter( 8546 new PreferredActivity(filter, match, set, activity, userId)); 8547 scheduleWriteSettingsLocked(); 8548 } 8549 } 8550 8551 public void replacePreferredActivity(IntentFilter filter, int match, 8552 ComponentName[] set, ComponentName activity) { 8553 if (filter.countActions() != 1) { 8554 throw new IllegalArgumentException( 8555 "replacePreferredActivity expects filter to have only 1 action."); 8556 } 8557 if (filter.countCategories() != 1) { 8558 throw new IllegalArgumentException( 8559 "replacePreferredActivity expects filter to have only 1 category."); 8560 } 8561 if (filter.countDataAuthorities() != 0 8562 || filter.countDataPaths() != 0 8563 || filter.countDataSchemes() != 0 8564 || filter.countDataTypes() != 0) { 8565 throw new IllegalArgumentException( 8566 "replacePreferredActivity expects filter to have no data authorities, " + 8567 "paths, schemes or types."); 8568 } 8569 synchronized (mPackages) { 8570 if (mContext.checkCallingOrSelfPermission( 8571 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8572 != PackageManager.PERMISSION_GRANTED) { 8573 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 8574 < Build.VERSION_CODES.FROYO) { 8575 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 8576 + Binder.getCallingUid()); 8577 return; 8578 } 8579 mContext.enforceCallingOrSelfPermission( 8580 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8581 } 8582 8583 final int callingUserId = UserHandle.getCallingUserId(); 8584 ArrayList<PreferredActivity> removed = null; 8585 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8586 String action = filter.getAction(0); 8587 String category = filter.getCategory(0); 8588 while (it.hasNext()) { 8589 PreferredActivity pa = it.next(); 8590 if (pa.mUserId != callingUserId) continue; 8591 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) { 8592 if (removed == null) { 8593 removed = new ArrayList<PreferredActivity>(); 8594 } 8595 removed.add(pa); 8596 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":"); 8597 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 8598 } 8599 } 8600 if (removed != null) { 8601 for (int i=0; i<removed.size(); i++) { 8602 PreferredActivity pa = removed.get(i); 8603 mSettings.mPreferredActivities.removeFilter(pa); 8604 } 8605 } 8606 addPreferredActivity(filter, match, set, activity, callingUserId); 8607 } 8608 } 8609 8610 public void clearPackagePreferredActivities(String packageName) { 8611 final int uid = Binder.getCallingUid(); 8612 // writer 8613 synchronized (mPackages) { 8614 PackageParser.Package pkg = mPackages.get(packageName); 8615 if (pkg == null || pkg.applicationInfo.uid != uid) { 8616 if (mContext.checkCallingOrSelfPermission( 8617 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8618 != PackageManager.PERMISSION_GRANTED) { 8619 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 8620 < Build.VERSION_CODES.FROYO) { 8621 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 8622 + Binder.getCallingUid()); 8623 return; 8624 } 8625 mContext.enforceCallingOrSelfPermission( 8626 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8627 } 8628 } 8629 8630 if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) { 8631 scheduleWriteSettingsLocked(); 8632 } 8633 } 8634 } 8635 8636 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 8637 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 8638 ArrayList<PreferredActivity> removed = null; 8639 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8640 while (it.hasNext()) { 8641 PreferredActivity pa = it.next(); 8642 if (userId != UserHandle.USER_ALL && pa.mUserId != userId) { 8643 continue; 8644 } 8645 if (pa.mPref.mComponent.getPackageName().equals(packageName)) { 8646 if (removed == null) { 8647 removed = new ArrayList<PreferredActivity>(); 8648 } 8649 removed.add(pa); 8650 } 8651 } 8652 if (removed != null) { 8653 for (int i=0; i<removed.size(); i++) { 8654 PreferredActivity pa = removed.get(i); 8655 mSettings.mPreferredActivities.removeFilter(pa); 8656 } 8657 return true; 8658 } 8659 return false; 8660 } 8661 8662 public int getPreferredActivities(List<IntentFilter> outFilters, 8663 List<ComponentName> outActivities, String packageName) { 8664 8665 int num = 0; 8666 final int userId = UserHandle.getCallingUserId(); 8667 // reader 8668 synchronized (mPackages) { 8669 final Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8670 while (it.hasNext()) { 8671 final PreferredActivity pa = it.next(); 8672 if (pa.mUserId != userId) { 8673 continue; 8674 } 8675 if (packageName == null 8676 || pa.mPref.mComponent.getPackageName().equals(packageName)) { 8677 if (outFilters != null) { 8678 outFilters.add(new IntentFilter(pa)); 8679 } 8680 if (outActivities != null) { 8681 outActivities.add(pa.mPref.mComponent); 8682 } 8683 } 8684 } 8685 } 8686 8687 return num; 8688 } 8689 8690 @Override 8691 public void setApplicationEnabledSetting(String appPackageName, 8692 int newState, int flags, int userId) { 8693 if (!sUserManager.exists(userId)) return; 8694 setEnabledSetting(appPackageName, null, newState, flags, userId); 8695 } 8696 8697 @Override 8698 public void setComponentEnabledSetting(ComponentName componentName, 8699 int newState, int flags, int userId) { 8700 if (!sUserManager.exists(userId)) return; 8701 setEnabledSetting(componentName.getPackageName(), 8702 componentName.getClassName(), newState, flags, userId); 8703 } 8704 8705 private void setEnabledSetting( 8706 final String packageName, String className, int newState, final int flags, int userId) { 8707 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 8708 || newState == COMPONENT_ENABLED_STATE_ENABLED 8709 || newState == COMPONENT_ENABLED_STATE_DISABLED 8710 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) { 8711 throw new IllegalArgumentException("Invalid new component state: " 8712 + newState); 8713 } 8714 PackageSetting pkgSetting; 8715 final int uid = Binder.getCallingUid(); 8716 final int permission = mContext.checkCallingPermission( 8717 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 8718 enforceCrossUserPermission(uid, userId, false, "set enabled"); 8719 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 8720 boolean sendNow = false; 8721 boolean isApp = (className == null); 8722 String componentName = isApp ? packageName : className; 8723 int packageUid = -1; 8724 ArrayList<String> components; 8725 8726 // writer 8727 synchronized (mPackages) { 8728 pkgSetting = mSettings.mPackages.get(packageName); 8729 if (pkgSetting == null) { 8730 if (className == null) { 8731 throw new IllegalArgumentException( 8732 "Unknown package: " + packageName); 8733 } 8734 throw new IllegalArgumentException( 8735 "Unknown component: " + packageName 8736 + "/" + className); 8737 } 8738 // Allow root and verify that userId is not being specified by a different user 8739 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 8740 throw new SecurityException( 8741 "Permission Denial: attempt to change component state from pid=" 8742 + Binder.getCallingPid() 8743 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 8744 } 8745 if (className == null) { 8746 // We're dealing with an application/package level state change 8747 if (pkgSetting.getEnabled(userId) == newState) { 8748 // Nothing to do 8749 return; 8750 } 8751 pkgSetting.setEnabled(newState, userId); 8752 // pkgSetting.pkg.mSetEnabled = newState; 8753 } else { 8754 // We're dealing with a component level state change 8755 // First, verify that this is a valid class name. 8756 PackageParser.Package pkg = pkgSetting.pkg; 8757 if (pkg == null || !pkg.hasComponentClassName(className)) { 8758 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 8759 throw new IllegalArgumentException("Component class " + className 8760 + " does not exist in " + packageName); 8761 } else { 8762 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 8763 + className + " does not exist in " + packageName); 8764 } 8765 } 8766 switch (newState) { 8767 case COMPONENT_ENABLED_STATE_ENABLED: 8768 if (!pkgSetting.enableComponentLPw(className, userId)) { 8769 return; 8770 } 8771 break; 8772 case COMPONENT_ENABLED_STATE_DISABLED: 8773 if (!pkgSetting.disableComponentLPw(className, userId)) { 8774 return; 8775 } 8776 break; 8777 case COMPONENT_ENABLED_STATE_DEFAULT: 8778 if (!pkgSetting.restoreComponentLPw(className, userId)) { 8779 return; 8780 } 8781 break; 8782 default: 8783 Slog.e(TAG, "Invalid new component state: " + newState); 8784 return; 8785 } 8786 } 8787 mSettings.writePackageRestrictionsLPr(userId); 8788 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 8789 components = mPendingBroadcasts.get(packageName); 8790 final boolean newPackage = components == null; 8791 if (newPackage) { 8792 components = new ArrayList<String>(); 8793 } 8794 if (!components.contains(componentName)) { 8795 components.add(componentName); 8796 } 8797 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 8798 sendNow = true; 8799 // Purge entry from pending broadcast list if another one exists already 8800 // since we are sending one right away. 8801 mPendingBroadcasts.remove(packageName); 8802 } else { 8803 if (newPackage) { 8804 mPendingBroadcasts.put(packageName, components); 8805 } 8806 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 8807 // Schedule a message 8808 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 8809 } 8810 } 8811 } 8812 8813 long callingId = Binder.clearCallingIdentity(); 8814 try { 8815 if (sendNow) { 8816 sendPackageChangedBroadcast(packageName, 8817 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 8818 } 8819 } finally { 8820 Binder.restoreCallingIdentity(callingId); 8821 } 8822 } 8823 8824 private void sendPackageChangedBroadcast(String packageName, 8825 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 8826 if (DEBUG_INSTALL) 8827 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 8828 + componentNames); 8829 Bundle extras = new Bundle(4); 8830 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 8831 String nameList[] = new String[componentNames.size()]; 8832 componentNames.toArray(nameList); 8833 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 8834 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 8835 extras.putInt(Intent.EXTRA_UID, packageUid); 8836 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 8837 new int[] {UserHandle.getUserId(packageUid)}); 8838 } 8839 8840 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 8841 if (!sUserManager.exists(userId)) return; 8842 final int uid = Binder.getCallingUid(); 8843 final int permission = mContext.checkCallingOrSelfPermission( 8844 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 8845 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 8846 enforceCrossUserPermission(uid, userId, true, "stop package"); 8847 // writer 8848 synchronized (mPackages) { 8849 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 8850 uid, userId)) { 8851 scheduleWritePackageRestrictionsLocked(userId); 8852 } 8853 } 8854 } 8855 8856 public String getInstallerPackageName(String packageName) { 8857 // reader 8858 synchronized (mPackages) { 8859 return mSettings.getInstallerPackageNameLPr(packageName); 8860 } 8861 } 8862 8863 @Override 8864 public int getApplicationEnabledSetting(String packageName, int userId) { 8865 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 8866 int uid = Binder.getCallingUid(); 8867 enforceCrossUserPermission(uid, userId, false, "get enabled"); 8868 // reader 8869 synchronized (mPackages) { 8870 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 8871 } 8872 } 8873 8874 @Override 8875 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 8876 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 8877 int uid = Binder.getCallingUid(); 8878 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 8879 // reader 8880 synchronized (mPackages) { 8881 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 8882 } 8883 } 8884 8885 public void enterSafeMode() { 8886 enforceSystemOrRoot("Only the system can request entering safe mode"); 8887 8888 if (!mSystemReady) { 8889 mSafeMode = true; 8890 } 8891 } 8892 8893 public void systemReady() { 8894 mSystemReady = true; 8895 8896 // Read the compatibilty setting when the system is ready. 8897 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt( 8898 mContext.getContentResolver(), 8899 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1; 8900 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 8901 if (DEBUG_SETTINGS) { 8902 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 8903 } 8904 } 8905 8906 public boolean isSafeMode() { 8907 return mSafeMode; 8908 } 8909 8910 public boolean hasSystemUidErrors() { 8911 return mHasSystemUidErrors; 8912 } 8913 8914 static String arrayToString(int[] array) { 8915 StringBuffer buf = new StringBuffer(128); 8916 buf.append('['); 8917 if (array != null) { 8918 for (int i=0; i<array.length; i++) { 8919 if (i > 0) buf.append(", "); 8920 buf.append(array[i]); 8921 } 8922 } 8923 buf.append(']'); 8924 return buf.toString(); 8925 } 8926 8927 static class DumpState { 8928 public static final int DUMP_LIBS = 1 << 0; 8929 8930 public static final int DUMP_FEATURES = 1 << 1; 8931 8932 public static final int DUMP_RESOLVERS = 1 << 2; 8933 8934 public static final int DUMP_PERMISSIONS = 1 << 3; 8935 8936 public static final int DUMP_PACKAGES = 1 << 4; 8937 8938 public static final int DUMP_SHARED_USERS = 1 << 5; 8939 8940 public static final int DUMP_MESSAGES = 1 << 6; 8941 8942 public static final int DUMP_PROVIDERS = 1 << 7; 8943 8944 public static final int DUMP_VERIFIERS = 1 << 8; 8945 8946 public static final int DUMP_PREFERRED = 1 << 9; 8947 8948 public static final int DUMP_PREFERRED_XML = 1 << 10; 8949 8950 public static final int OPTION_SHOW_FILTERS = 1 << 0; 8951 8952 private int mTypes; 8953 8954 private int mOptions; 8955 8956 private boolean mTitlePrinted; 8957 8958 private SharedUserSetting mSharedUser; 8959 8960 public boolean isDumping(int type) { 8961 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 8962 return true; 8963 } 8964 8965 return (mTypes & type) != 0; 8966 } 8967 8968 public void setDump(int type) { 8969 mTypes |= type; 8970 } 8971 8972 public boolean isOptionEnabled(int option) { 8973 return (mOptions & option) != 0; 8974 } 8975 8976 public void setOptionEnabled(int option) { 8977 mOptions |= option; 8978 } 8979 8980 public boolean onTitlePrinted() { 8981 final boolean printed = mTitlePrinted; 8982 mTitlePrinted = true; 8983 return printed; 8984 } 8985 8986 public boolean getTitlePrinted() { 8987 return mTitlePrinted; 8988 } 8989 8990 public void setTitlePrinted(boolean enabled) { 8991 mTitlePrinted = enabled; 8992 } 8993 8994 public SharedUserSetting getSharedUser() { 8995 return mSharedUser; 8996 } 8997 8998 public void setSharedUser(SharedUserSetting user) { 8999 mSharedUser = user; 9000 } 9001 } 9002 9003 @Override 9004 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9005 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 9006 != PackageManager.PERMISSION_GRANTED) { 9007 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 9008 + Binder.getCallingPid() 9009 + ", uid=" + Binder.getCallingUid() 9010 + " without permission " 9011 + android.Manifest.permission.DUMP); 9012 return; 9013 } 9014 9015 DumpState dumpState = new DumpState(); 9016 9017 String packageName = null; 9018 9019 int opti = 0; 9020 while (opti < args.length) { 9021 String opt = args[opti]; 9022 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 9023 break; 9024 } 9025 opti++; 9026 if ("-a".equals(opt)) { 9027 // Right now we only know how to print all. 9028 } else if ("-h".equals(opt)) { 9029 pw.println("Package manager dump options:"); 9030 pw.println(" [-h] [-f] [cmd] ..."); 9031 pw.println(" -f: print details of intent filters"); 9032 pw.println(" -h: print this help"); 9033 pw.println(" cmd may be one of:"); 9034 pw.println(" l[ibraries]: list known shared libraries"); 9035 pw.println(" f[ibraries]: list device features"); 9036 pw.println(" r[esolvers]: dump intent resolvers"); 9037 pw.println(" perm[issions]: dump permissions"); 9038 pw.println(" pref[erred]: print preferred package settings"); 9039 pw.println(" preferred-xml: print preferred package settings as xml"); 9040 pw.println(" prov[iders]: dump content providers"); 9041 pw.println(" p[ackages]: dump installed packages"); 9042 pw.println(" s[hared-users]: dump shared user IDs"); 9043 pw.println(" m[essages]: print collected runtime messages"); 9044 pw.println(" v[erifiers]: print package verifier info"); 9045 pw.println(" <package.name>: info about given package"); 9046 return; 9047 } else if ("-f".equals(opt)) { 9048 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 9049 } else { 9050 pw.println("Unknown argument: " + opt + "; use -h for help"); 9051 } 9052 } 9053 9054 // Is the caller requesting to dump a particular piece of data? 9055 if (opti < args.length) { 9056 String cmd = args[opti]; 9057 opti++; 9058 // Is this a package name? 9059 if ("android".equals(cmd) || cmd.contains(".")) { 9060 packageName = cmd; 9061 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 9062 dumpState.setDump(DumpState.DUMP_LIBS); 9063 } else if ("f".equals(cmd) || "features".equals(cmd)) { 9064 dumpState.setDump(DumpState.DUMP_FEATURES); 9065 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 9066 dumpState.setDump(DumpState.DUMP_RESOLVERS); 9067 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 9068 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 9069 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 9070 dumpState.setDump(DumpState.DUMP_PREFERRED); 9071 } else if ("preferred-xml".equals(cmd)) { 9072 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 9073 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 9074 dumpState.setDump(DumpState.DUMP_PACKAGES); 9075 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 9076 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 9077 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 9078 dumpState.setDump(DumpState.DUMP_PROVIDERS); 9079 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 9080 dumpState.setDump(DumpState.DUMP_MESSAGES); 9081 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 9082 dumpState.setDump(DumpState.DUMP_VERIFIERS); 9083 } 9084 } 9085 9086 // reader 9087 synchronized (mPackages) { 9088 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 9089 if (dumpState.onTitlePrinted()) 9090 pw.println(" "); 9091 pw.println("Verifiers:"); 9092 pw.print(" Required: "); 9093 pw.print(mRequiredVerifierPackage); 9094 pw.print(" (uid="); 9095 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 9096 pw.println(")"); 9097 } 9098 9099 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 9100 if (dumpState.onTitlePrinted()) 9101 pw.println(" "); 9102 pw.println("Libraries:"); 9103 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 9104 while (it.hasNext()) { 9105 String name = it.next(); 9106 pw.print(" "); 9107 pw.print(name); 9108 pw.print(" -> "); 9109 pw.println(mSharedLibraries.get(name)); 9110 } 9111 } 9112 9113 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 9114 if (dumpState.onTitlePrinted()) 9115 pw.println(" "); 9116 pw.println("Features:"); 9117 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 9118 while (it.hasNext()) { 9119 String name = it.next(); 9120 pw.print(" "); 9121 pw.println(name); 9122 } 9123 } 9124 9125 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 9126 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 9127 : "Activity Resolver Table:", " ", packageName, 9128 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9129 dumpState.setTitlePrinted(true); 9130 } 9131 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 9132 : "Receiver Resolver Table:", " ", packageName, 9133 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9134 dumpState.setTitlePrinted(true); 9135 } 9136 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 9137 : "Service Resolver Table:", " ", packageName, 9138 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9139 dumpState.setTitlePrinted(true); 9140 } 9141 } 9142 9143 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 9144 if (mSettings.mPreferredActivities.dump(pw, 9145 dumpState.getTitlePrinted() ? "\nPreferred Activities:" 9146 : "Preferred Activities:", " ", 9147 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9148 dumpState.setTitlePrinted(true); 9149 } 9150 } 9151 9152 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 9153 pw.flush(); 9154 FileOutputStream fout = new FileOutputStream(fd); 9155 BufferedOutputStream str = new BufferedOutputStream(fout); 9156 XmlSerializer serializer = new FastXmlSerializer(); 9157 try { 9158 serializer.setOutput(str, "utf-8"); 9159 serializer.startDocument(null, true); 9160 serializer.setFeature( 9161 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 9162 mSettings.writePreferredActivitiesLPr(serializer); 9163 serializer.endDocument(); 9164 serializer.flush(); 9165 } catch (IllegalArgumentException e) { 9166 pw.println("Failed writing: " + e); 9167 } catch (IllegalStateException e) { 9168 pw.println("Failed writing: " + e); 9169 } catch (IOException e) { 9170 pw.println("Failed writing: " + e); 9171 } 9172 } 9173 9174 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 9175 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 9176 } 9177 9178 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 9179 boolean printedSomething = false; 9180 for (PackageParser.Provider p : mProvidersByComponent.values()) { 9181 if (packageName != null && !packageName.equals(p.info.packageName)) { 9182 continue; 9183 } 9184 if (!printedSomething) { 9185 if (dumpState.onTitlePrinted()) 9186 pw.println(" "); 9187 pw.println("Registered ContentProviders:"); 9188 printedSomething = true; 9189 } 9190 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":"); 9191 pw.print(" "); pw.println(p.toString()); 9192 } 9193 printedSomething = false; 9194 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) { 9195 PackageParser.Provider p = entry.getValue(); 9196 if (packageName != null && !packageName.equals(p.info.packageName)) { 9197 continue; 9198 } 9199 if (!printedSomething) { 9200 if (dumpState.onTitlePrinted()) 9201 pw.println(" "); 9202 pw.println("ContentProvider Authorities:"); 9203 printedSomething = true; 9204 } 9205 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 9206 pw.print(" "); pw.println(p.toString()); 9207 if (p.info != null && p.info.applicationInfo != null) { 9208 final String appInfo = p.info.applicationInfo.toString(); 9209 pw.print(" applicationInfo="); pw.println(appInfo); 9210 } 9211 } 9212 } 9213 9214 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 9215 mSettings.dumpPackagesLPr(pw, packageName, dumpState); 9216 } 9217 9218 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 9219 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 9220 } 9221 9222 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 9223 if (dumpState.onTitlePrinted()) 9224 pw.println(" "); 9225 mSettings.dumpReadMessagesLPr(pw, dumpState); 9226 9227 pw.println(" "); 9228 pw.println("Package warning messages:"); 9229 final File fname = getSettingsProblemFile(); 9230 FileInputStream in = null; 9231 try { 9232 in = new FileInputStream(fname); 9233 final int avail = in.available(); 9234 final byte[] data = new byte[avail]; 9235 in.read(data); 9236 pw.print(new String(data)); 9237 } catch (FileNotFoundException e) { 9238 } catch (IOException e) { 9239 } finally { 9240 if (in != null) { 9241 try { 9242 in.close(); 9243 } catch (IOException e) { 9244 } 9245 } 9246 } 9247 } 9248 } 9249 } 9250 9251 // ------- apps on sdcard specific code ------- 9252 static final boolean DEBUG_SD_INSTALL = false; 9253 9254 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 9255 9256 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 9257 9258 private boolean mMediaMounted = false; 9259 9260 private String getEncryptKey() { 9261 try { 9262 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 9263 SD_ENCRYPTION_KEYSTORE_NAME); 9264 if (sdEncKey == null) { 9265 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 9266 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 9267 if (sdEncKey == null) { 9268 Slog.e(TAG, "Failed to create encryption keys"); 9269 return null; 9270 } 9271 } 9272 return sdEncKey; 9273 } catch (NoSuchAlgorithmException nsae) { 9274 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 9275 return null; 9276 } catch (IOException ioe) { 9277 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 9278 return null; 9279 } 9280 9281 } 9282 9283 /* package */static String getTempContainerId() { 9284 int tmpIdx = 1; 9285 String list[] = PackageHelper.getSecureContainerList(); 9286 if (list != null) { 9287 for (final String name : list) { 9288 // Ignore null and non-temporary container entries 9289 if (name == null || !name.startsWith(mTempContainerPrefix)) { 9290 continue; 9291 } 9292 9293 String subStr = name.substring(mTempContainerPrefix.length()); 9294 try { 9295 int cid = Integer.parseInt(subStr); 9296 if (cid >= tmpIdx) { 9297 tmpIdx = cid + 1; 9298 } 9299 } catch (NumberFormatException e) { 9300 } 9301 } 9302 } 9303 return mTempContainerPrefix + tmpIdx; 9304 } 9305 9306 /* 9307 * Update media status on PackageManager. 9308 */ 9309 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 9310 int callingUid = Binder.getCallingUid(); 9311 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 9312 throw new SecurityException("Media status can only be updated by the system"); 9313 } 9314 // reader; this apparently protects mMediaMounted, but should probably 9315 // be a different lock in that case. 9316 synchronized (mPackages) { 9317 Log.i(TAG, "Updating external media status from " 9318 + (mMediaMounted ? "mounted" : "unmounted") + " to " 9319 + (mediaStatus ? "mounted" : "unmounted")); 9320 if (DEBUG_SD_INSTALL) 9321 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 9322 + ", mMediaMounted=" + mMediaMounted); 9323 if (mediaStatus == mMediaMounted) { 9324 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 9325 : 0, -1); 9326 mHandler.sendMessage(msg); 9327 return; 9328 } 9329 mMediaMounted = mediaStatus; 9330 } 9331 // Queue up an async operation since the package installation may take a 9332 // little while. 9333 mHandler.post(new Runnable() { 9334 public void run() { 9335 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 9336 } 9337 }); 9338 } 9339 9340 /** 9341 * Called by MountService when the initial ASECs to scan are available. 9342 * Should block until all the ASEC containers are finished being scanned. 9343 */ 9344 public void scanAvailableAsecs() { 9345 updateExternalMediaStatusInner(true, false, false); 9346 } 9347 9348 /* 9349 * Collect information of applications on external media, map them against 9350 * existing containers and update information based on current mount status. 9351 * Please note that we always have to report status if reportStatus has been 9352 * set to true especially when unloading packages. 9353 */ 9354 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 9355 boolean externalStorage) { 9356 // Collection of uids 9357 int uidArr[] = null; 9358 // Collection of stale containers 9359 HashSet<String> removeCids = new HashSet<String>(); 9360 // Collection of packages on external media with valid containers. 9361 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 9362 // Get list of secure containers. 9363 final String list[] = PackageHelper.getSecureContainerList(); 9364 if (list == null || list.length == 0) { 9365 Log.i(TAG, "No secure containers on sdcard"); 9366 } else { 9367 // Process list of secure containers and categorize them 9368 // as active or stale based on their package internal state. 9369 int uidList[] = new int[list.length]; 9370 int num = 0; 9371 // reader 9372 synchronized (mPackages) { 9373 for (String cid : list) { 9374 if (DEBUG_SD_INSTALL) 9375 Log.i(TAG, "Processing container " + cid); 9376 String pkgName = getAsecPackageName(cid); 9377 if (pkgName == null) { 9378 if (DEBUG_SD_INSTALL) 9379 Log.i(TAG, "Container : " + cid + " stale"); 9380 removeCids.add(cid); 9381 continue; 9382 } 9383 if (DEBUG_SD_INSTALL) 9384 Log.i(TAG, "Looking for pkg : " + pkgName); 9385 9386 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9387 if (ps == null) { 9388 Log.i(TAG, "Deleting container with no matching settings " + cid); 9389 removeCids.add(cid); 9390 continue; 9391 } 9392 9393 /* 9394 * Skip packages that are not external if we're unmounting 9395 * external storage. 9396 */ 9397 if (externalStorage && !isMounted && !isExternal(ps)) { 9398 continue; 9399 } 9400 9401 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps)); 9402 // The package status is changed only if the code path 9403 // matches between settings and the container id. 9404 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 9405 if (DEBUG_SD_INSTALL) { 9406 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 9407 + " at code path: " + ps.codePathString); 9408 } 9409 9410 // We do have a valid package installed on sdcard 9411 processCids.put(args, ps.codePathString); 9412 final int uid = ps.appId; 9413 if (uid != -1) { 9414 uidList[num++] = uid; 9415 } 9416 } else { 9417 Log.i(TAG, "Deleting stale container for " + cid); 9418 removeCids.add(cid); 9419 } 9420 } 9421 } 9422 9423 if (num > 0) { 9424 // Sort uid list 9425 Arrays.sort(uidList, 0, num); 9426 // Throw away duplicates 9427 uidArr = new int[num]; 9428 uidArr[0] = uidList[0]; 9429 int di = 0; 9430 for (int i = 1; i < num; i++) { 9431 if (uidList[i - 1] != uidList[i]) { 9432 uidArr[di++] = uidList[i]; 9433 } 9434 } 9435 } 9436 } 9437 // Process packages with valid entries. 9438 if (isMounted) { 9439 if (DEBUG_SD_INSTALL) 9440 Log.i(TAG, "Loading packages"); 9441 loadMediaPackages(processCids, uidArr, removeCids); 9442 startCleaningPackages(-1); 9443 } else { 9444 if (DEBUG_SD_INSTALL) 9445 Log.i(TAG, "Unloading packages"); 9446 unloadMediaPackages(processCids, uidArr, reportStatus); 9447 } 9448 } 9449 9450 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList, 9451 int uidArr[], IIntentReceiver finishedReceiver) { 9452 int size = pkgList.size(); 9453 if (size > 0) { 9454 // Send broadcasts here 9455 Bundle extras = new Bundle(); 9456 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 9457 .toArray(new String[size])); 9458 if (uidArr != null) { 9459 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 9460 } 9461 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 9462 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 9463 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 9464 } 9465 } 9466 9467 /* 9468 * Look at potentially valid container ids from processCids If package 9469 * information doesn't match the one on record or package scanning fails, 9470 * the cid is added to list of removeCids. We currently don't delete stale 9471 * containers. 9472 */ 9473 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 9474 HashSet<String> removeCids) { 9475 ArrayList<String> pkgList = new ArrayList<String>(); 9476 Set<AsecInstallArgs> keys = processCids.keySet(); 9477 boolean doGc = false; 9478 for (AsecInstallArgs args : keys) { 9479 String codePath = processCids.get(args); 9480 if (DEBUG_SD_INSTALL) 9481 Log.i(TAG, "Loading container : " + args.cid); 9482 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9483 try { 9484 // Make sure there are no container errors first. 9485 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 9486 Slog.e(TAG, "Failed to mount cid : " + args.cid 9487 + " when installing from sdcard"); 9488 continue; 9489 } 9490 // Check code path here. 9491 if (codePath == null || !codePath.equals(args.getCodePath())) { 9492 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 9493 + " does not match one in settings " + codePath); 9494 continue; 9495 } 9496 // Parse package 9497 int parseFlags = mDefParseFlags; 9498 if (args.isExternal()) { 9499 parseFlags |= PackageParser.PARSE_ON_SDCARD; 9500 } 9501 if (args.isFwdLocked()) { 9502 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 9503 } 9504 9505 doGc = true; 9506 synchronized (mInstallLock) { 9507 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 9508 0, 0, null); 9509 // Scan the package 9510 if (pkg != null) { 9511 /* 9512 * TODO why is the lock being held? doPostInstall is 9513 * called in other places without the lock. This needs 9514 * to be straightened out. 9515 */ 9516 // writer 9517 synchronized (mPackages) { 9518 retCode = PackageManager.INSTALL_SUCCEEDED; 9519 pkgList.add(pkg.packageName); 9520 // Post process args 9521 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 9522 pkg.applicationInfo.uid); 9523 } 9524 } else { 9525 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 9526 } 9527 } 9528 9529 } finally { 9530 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 9531 // Don't destroy container here. Wait till gc clears things 9532 // up. 9533 removeCids.add(args.cid); 9534 } 9535 } 9536 } 9537 // writer 9538 synchronized (mPackages) { 9539 // If the platform SDK has changed since the last time we booted, 9540 // we need to re-grant app permission to catch any new ones that 9541 // appear. This is really a hack, and means that apps can in some 9542 // cases get permissions that the user didn't initially explicitly 9543 // allow... it would be nice to have some better way to handle 9544 // this situation. 9545 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 9546 if (regrantPermissions) 9547 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 9548 + mSdkVersion + "; regranting permissions for external storage"); 9549 mSettings.mExternalSdkPlatform = mSdkVersion; 9550 9551 // Make sure group IDs have been assigned, and any permission 9552 // changes in other apps are accounted for 9553 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 9554 | (regrantPermissions 9555 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 9556 : 0)); 9557 // can downgrade to reader 9558 // Persist settings 9559 mSettings.writeLPr(); 9560 } 9561 // Send a broadcast to let everyone know we are done processing 9562 if (pkgList.size() > 0) { 9563 sendResourcesChangedBroadcast(true, pkgList, uidArr, null); 9564 } 9565 // Force gc to avoid any stale parser references that we might have. 9566 if (doGc) { 9567 Runtime.getRuntime().gc(); 9568 } 9569 // List stale containers and destroy stale temporary containers. 9570 if (removeCids != null) { 9571 for (String cid : removeCids) { 9572 if (cid.startsWith(mTempContainerPrefix)) { 9573 Log.i(TAG, "Destroying stale temporary container " + cid); 9574 PackageHelper.destroySdDir(cid); 9575 } else { 9576 Log.w(TAG, "Container " + cid + " is stale"); 9577 } 9578 } 9579 } 9580 } 9581 9582 /* 9583 * Utility method to unload a list of specified containers 9584 */ 9585 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 9586 // Just unmount all valid containers. 9587 for (AsecInstallArgs arg : cidArgs) { 9588 synchronized (mInstallLock) { 9589 arg.doPostDeleteLI(false); 9590 } 9591 } 9592 } 9593 9594 /* 9595 * Unload packages mounted on external media. This involves deleting package 9596 * data from internal structures, sending broadcasts about diabled packages, 9597 * gc'ing to free up references, unmounting all secure containers 9598 * corresponding to packages on external media, and posting a 9599 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 9600 * that we always have to post this message if status has been requested no 9601 * matter what. 9602 */ 9603 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 9604 final boolean reportStatus) { 9605 if (DEBUG_SD_INSTALL) 9606 Log.i(TAG, "unloading media packages"); 9607 ArrayList<String> pkgList = new ArrayList<String>(); 9608 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 9609 final Set<AsecInstallArgs> keys = processCids.keySet(); 9610 for (AsecInstallArgs args : keys) { 9611 String pkgName = args.getPackageName(); 9612 if (DEBUG_SD_INSTALL) 9613 Log.i(TAG, "Trying to unload pkg : " + pkgName); 9614 // Delete package internally 9615 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 9616 synchronized (mInstallLock) { 9617 boolean res = deletePackageLI(pkgName, null, false, 9618 PackageManager.DELETE_KEEP_DATA, outInfo, false); 9619 if (res) { 9620 pkgList.add(pkgName); 9621 } else { 9622 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 9623 failedList.add(args); 9624 } 9625 } 9626 } 9627 9628 // reader 9629 synchronized (mPackages) { 9630 // We didn't update the settings after removing each package; 9631 // write them now for all packages. 9632 mSettings.writeLPr(); 9633 } 9634 9635 // We have to absolutely send UPDATED_MEDIA_STATUS only 9636 // after confirming that all the receivers processed the ordered 9637 // broadcast when packages get disabled, force a gc to clean things up. 9638 // and unload all the containers. 9639 if (pkgList.size() > 0) { 9640 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() { 9641 public void performReceive(Intent intent, int resultCode, String data, 9642 Bundle extras, boolean ordered, boolean sticky, 9643 int sendingUser) throws RemoteException { 9644 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 9645 reportStatus ? 1 : 0, 1, keys); 9646 mHandler.sendMessage(msg); 9647 } 9648 }); 9649 } else { 9650 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 9651 keys); 9652 mHandler.sendMessage(msg); 9653 } 9654 } 9655 9656 /** Binder call */ 9657 @Override 9658 public void movePackage(final String packageName, final IPackageMoveObserver observer, 9659 final int flags) { 9660 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 9661 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 9662 int returnCode = PackageManager.MOVE_SUCCEEDED; 9663 int currFlags = 0; 9664 int newFlags = 0; 9665 // reader 9666 synchronized (mPackages) { 9667 PackageParser.Package pkg = mPackages.get(packageName); 9668 if (pkg == null) { 9669 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9670 } else { 9671 // Disable moving fwd locked apps and system packages 9672 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 9673 Slog.w(TAG, "Cannot move system application"); 9674 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 9675 } else if (pkg.mOperationPending) { 9676 Slog.w(TAG, "Attempt to move package which has pending operations"); 9677 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 9678 } else { 9679 // Find install location first 9680 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 9681 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 9682 Slog.w(TAG, "Ambigous flags specified for move location."); 9683 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9684 } else { 9685 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 9686 : PackageManager.INSTALL_INTERNAL; 9687 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 9688 : PackageManager.INSTALL_INTERNAL; 9689 9690 if (newFlags == currFlags) { 9691 Slog.w(TAG, "No move required. Trying to move to same location"); 9692 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9693 } else { 9694 if (isForwardLocked(pkg)) { 9695 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9696 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9697 } 9698 } 9699 } 9700 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9701 pkg.mOperationPending = true; 9702 } 9703 } 9704 } 9705 9706 /* 9707 * TODO this next block probably shouldn't be inside the lock. We 9708 * can't guarantee these won't change after this is fired off 9709 * anyway. 9710 */ 9711 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 9712 processPendingMove(new MoveParams(null, observer, 0, packageName, 9713 null, -1, user), 9714 returnCode); 9715 } else { 9716 Message msg = mHandler.obtainMessage(INIT_COPY); 9717 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 9718 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir); 9719 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 9720 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user); 9721 msg.obj = mp; 9722 mHandler.sendMessage(msg); 9723 } 9724 } 9725 } 9726 9727 private void processPendingMove(final MoveParams mp, final int currentStatus) { 9728 // Queue up an async operation since the package deletion may take a 9729 // little while. 9730 mHandler.post(new Runnable() { 9731 public void run() { 9732 // TODO fix this; this does nothing. 9733 mHandler.removeCallbacks(this); 9734 int returnCode = currentStatus; 9735 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 9736 int uidArr[] = null; 9737 ArrayList<String> pkgList = null; 9738 synchronized (mPackages) { 9739 PackageParser.Package pkg = mPackages.get(mp.packageName); 9740 if (pkg == null) { 9741 Slog.w(TAG, " Package " + mp.packageName 9742 + " doesn't exist. Aborting move"); 9743 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9744 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 9745 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 9746 + mp.srcArgs.getCodePath() + " to " 9747 + pkg.applicationInfo.sourceDir 9748 + " Aborting move and returning error"); 9749 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9750 } else { 9751 uidArr = new int[] { 9752 pkg.applicationInfo.uid 9753 }; 9754 pkgList = new ArrayList<String>(); 9755 pkgList.add(mp.packageName); 9756 } 9757 } 9758 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9759 // Send resources unavailable broadcast 9760 sendResourcesChangedBroadcast(false, pkgList, uidArr, null); 9761 // Update package code and resource paths 9762 synchronized (mInstallLock) { 9763 synchronized (mPackages) { 9764 PackageParser.Package pkg = mPackages.get(mp.packageName); 9765 // Recheck for package again. 9766 if (pkg == null) { 9767 Slog.w(TAG, " Package " + mp.packageName 9768 + " doesn't exist. Aborting move"); 9769 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9770 } else if (!mp.srcArgs.getCodePath().equals( 9771 pkg.applicationInfo.sourceDir)) { 9772 Slog.w(TAG, "Package " + mp.packageName 9773 + " code path changed from " + mp.srcArgs.getCodePath() 9774 + " to " + pkg.applicationInfo.sourceDir 9775 + " Aborting move and returning error"); 9776 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9777 } else { 9778 final String oldCodePath = pkg.mPath; 9779 final String newCodePath = mp.targetArgs.getCodePath(); 9780 final String newResPath = mp.targetArgs.getResourcePath(); 9781 final String newNativePath = mp.targetArgs 9782 .getNativeLibraryPath(); 9783 9784 try { 9785 final File newNativeDir = new File(newNativePath); 9786 9787 final String libParentDir = newNativeDir.getParentFile() 9788 .getCanonicalPath(); 9789 if (newNativeDir.getParentFile().getCanonicalPath() 9790 .equals(pkg.applicationInfo.dataDir)) { 9791 if (mInstaller 9792 .unlinkNativeLibraryDirectory(pkg.applicationInfo.dataDir) < 0) { 9793 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9794 } else { 9795 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 9796 new File(newCodePath), newNativeDir); 9797 } 9798 } else { 9799 if (mInstaller.linkNativeLibraryDirectory( 9800 pkg.applicationInfo.dataDir, newNativePath) < 0) { 9801 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9802 } 9803 } 9804 } catch (IOException e) { 9805 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9806 } 9807 9808 9809 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9810 pkg.mPath = newCodePath; 9811 // Move dex files around 9812 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 9813 // Moving of dex files failed. Set 9814 // error code and abort move. 9815 pkg.mPath = pkg.mScanPath; 9816 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9817 } 9818 } 9819 9820 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9821 pkg.mScanPath = newCodePath; 9822 pkg.applicationInfo.sourceDir = newCodePath; 9823 pkg.applicationInfo.publicSourceDir = newResPath; 9824 pkg.applicationInfo.nativeLibraryDir = newNativePath; 9825 PackageSetting ps = (PackageSetting) pkg.mExtras; 9826 ps.codePath = new File(pkg.applicationInfo.sourceDir); 9827 ps.codePathString = ps.codePath.getPath(); 9828 ps.resourcePath = new File( 9829 pkg.applicationInfo.publicSourceDir); 9830 ps.resourcePathString = ps.resourcePath.getPath(); 9831 ps.nativeLibraryPathString = newNativePath; 9832 // Set the application info flag 9833 // correctly. 9834 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9835 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 9836 } else { 9837 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 9838 } 9839 ps.setFlags(pkg.applicationInfo.flags); 9840 mAppDirs.remove(oldCodePath); 9841 mAppDirs.put(newCodePath, pkg); 9842 // Persist settings 9843 mSettings.writeLPr(); 9844 } 9845 } 9846 } 9847 } 9848 // Send resources available broadcast 9849 sendResourcesChangedBroadcast(true, pkgList, uidArr, null); 9850 } 9851 } 9852 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 9853 // Clean up failed installation 9854 if (mp.targetArgs != null) { 9855 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 9856 -1); 9857 } 9858 } else { 9859 // Force a gc to clear things up. 9860 Runtime.getRuntime().gc(); 9861 // Delete older code 9862 synchronized (mInstallLock) { 9863 mp.srcArgs.doPostDeleteLI(true); 9864 } 9865 } 9866 9867 // Allow more operations on this file if we didn't fail because 9868 // an operation was already pending for this package. 9869 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 9870 synchronized (mPackages) { 9871 PackageParser.Package pkg = mPackages.get(mp.packageName); 9872 if (pkg != null) { 9873 pkg.mOperationPending = false; 9874 } 9875 } 9876 } 9877 9878 IPackageMoveObserver observer = mp.observer; 9879 if (observer != null) { 9880 try { 9881 observer.packageMoved(mp.packageName, returnCode); 9882 } catch (RemoteException e) { 9883 Log.i(TAG, "Observer no longer exists."); 9884 } 9885 } 9886 } 9887 }); 9888 } 9889 9890 public boolean setInstallLocation(int loc) { 9891 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 9892 null); 9893 if (getInstallLocation() == loc) { 9894 return true; 9895 } 9896 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 9897 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 9898 android.provider.Settings.System.putInt(mContext.getContentResolver(), 9899 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc); 9900 return true; 9901 } 9902 return false; 9903 } 9904 9905 public int getInstallLocation() { 9906 return android.provider.Settings.System.getInt(mContext.getContentResolver(), 9907 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, 9908 PackageHelper.APP_INSTALL_AUTO); 9909 } 9910 9911 /** Called by UserManagerService */ 9912 void cleanUpUserLILPw(int userHandle) { 9913 // Disable all the packages for the user first 9914 Set<Entry<String, PackageSetting>> entries = mSettings.mPackages.entrySet(); 9915 for (Entry<String, PackageSetting> entry : entries) { 9916 entry.getValue().removeUser(userHandle); 9917 } 9918 if (mDirtyUsers.remove(userHandle)); 9919 mSettings.removeUserLPr(userHandle); 9920 if (mInstaller != null) { 9921 // Technically, we shouldn't be doing this with the package lock 9922 // held. However, this is very rare, and there is already so much 9923 // other disk I/O going on, that we'll let it slide for now. 9924 mInstaller.removeUserDataDirs(userHandle); 9925 } 9926 } 9927 9928 /** Called by UserManagerService */ 9929 void createNewUserLILPw(int userHandle, File path) { 9930 if (mInstaller != null) { 9931 path.mkdir(); 9932 FileUtils.setPermissions(path.toString(), FileUtils.S_IRWXU | FileUtils.S_IRWXG 9933 | FileUtils.S_IXOTH, -1, -1); 9934 for (PackageSetting ps : mSettings.mPackages.values()) { 9935 // Only system apps are initially installed. 9936 ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle); 9937 // Need to create a data directory for all apps under this user. 9938 mInstaller.createUserData(ps.name, 9939 UserHandle.getUid(userHandle, ps.appId), userHandle); 9940 } 9941 mSettings.writePackageRestrictionsLPr(userHandle); 9942 } 9943 } 9944 9945 @Override 9946 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 9947 mContext.enforceCallingOrSelfPermission( 9948 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 9949 "Only package verification agents can read the verifier device identity"); 9950 9951 synchronized (mPackages) { 9952 return mSettings.getVerifierDeviceIdentityLPw(); 9953 } 9954 } 9955 9956 @Override 9957 public void setPermissionEnforced(String permission, boolean enforced) { 9958 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 9959 if (READ_EXTERNAL_STORAGE.equals(permission)) { 9960 synchronized (mPackages) { 9961 if (mSettings.mReadExternalStorageEnforced == null 9962 || mSettings.mReadExternalStorageEnforced != enforced) { 9963 mSettings.mReadExternalStorageEnforced = enforced; 9964 mSettings.writeLPr(); 9965 9966 // kill any non-foreground processes so we restart them and 9967 // grant/revoke the GID. 9968 final IActivityManager am = ActivityManagerNative.getDefault(); 9969 if (am != null) { 9970 final long token = Binder.clearCallingIdentity(); 9971 try { 9972 am.killProcessesBelowForeground("setPermissionEnforcement"); 9973 } catch (RemoteException e) { 9974 } finally { 9975 Binder.restoreCallingIdentity(token); 9976 } 9977 } 9978 } 9979 } 9980 } else { 9981 throw new IllegalArgumentException("No selective enforcement for " + permission); 9982 } 9983 } 9984 9985 @Override 9986 public boolean isPermissionEnforced(String permission) { 9987 synchronized (mPackages) { 9988 return isPermissionEnforcedLocked(permission); 9989 } 9990 } 9991 9992 private boolean isPermissionEnforcedLocked(String permission) { 9993 if (READ_EXTERNAL_STORAGE.equals(permission)) { 9994 if (mSettings.mReadExternalStorageEnforced != null) { 9995 return mSettings.mReadExternalStorageEnforced; 9996 } else { 9997 // if user hasn't defined, fall back to secure default 9998 return Secure.getInt(mContext.getContentResolver(), 9999 Secure.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0) != 0; 10000 } 10001 } else { 10002 return true; 10003 } 10004 } 10005 10006 public boolean isStorageLow() { 10007 final long token = Binder.clearCallingIdentity(); 10008 try { 10009 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 10010 .getService(DeviceStorageMonitorService.SERVICE); 10011 return dsm.isMemoryLow(); 10012 } finally { 10013 Binder.restoreCallingIdentity(token); 10014 } 10015 } 10016} 10017