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