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