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