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