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