PackageManagerService.java revision 8da429e80d1778d7bcfbfbd64355c70fb466b3ce
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, false); 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(false)); 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 if (userId != 0) { 2492 ri = new ResolveInfo(mResolveInfo); 2493 ri.activityInfo = new ActivityInfo(ri.activityInfo); 2494 ri.activityInfo.applicationInfo = new ApplicationInfo( 2495 ri.activityInfo.applicationInfo); 2496 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 2497 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 2498 return ri; 2499 } 2500 return mResolveInfo; 2501 } 2502 } 2503 return null; 2504 } 2505 2506 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, 2507 int flags, List<ResolveInfo> query, int priority, int userId) { 2508 if (!sUserManager.exists(userId)) return null; 2509 // writer 2510 synchronized (mPackages) { 2511 if (intent.getSelector() != null) { 2512 intent = intent.getSelector(); 2513 } 2514 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 2515 List<PreferredActivity> prefs = 2516 mSettings.mPreferredActivities.queryIntent(intent, resolvedType, 2517 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 2518 if (prefs != null && prefs.size() > 0) { 2519 // First figure out how good the original match set is. 2520 // We will only allow preferred activities that came 2521 // from the same match quality. 2522 int match = 0; 2523 2524 if (DEBUG_PREFERRED) { 2525 Log.v(TAG, "Figuring out best match..."); 2526 } 2527 2528 final int N = query.size(); 2529 for (int j=0; j<N; j++) { 2530 final ResolveInfo ri = query.get(j); 2531 if (DEBUG_PREFERRED) { 2532 Log.v(TAG, "Match for " + ri.activityInfo + ": 0x" 2533 + Integer.toHexString(match)); 2534 } 2535 if (ri.match > match) { 2536 match = ri.match; 2537 } 2538 } 2539 2540 if (DEBUG_PREFERRED) { 2541 Log.v(TAG, "Best match: 0x" + Integer.toHexString(match)); 2542 } 2543 2544 match &= IntentFilter.MATCH_CATEGORY_MASK; 2545 final int M = prefs.size(); 2546 for (int i=0; i<M; i++) { 2547 final PreferredActivity pa = prefs.get(i); 2548 if (pa.mUserId != userId) { 2549 continue; 2550 } 2551 if (pa.mPref.mMatch != match) { 2552 continue; 2553 } 2554 final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent, flags, userId); 2555 if (DEBUG_PREFERRED) { 2556 Log.v(TAG, "Got preferred activity:"); 2557 if (ai != null) { 2558 ai.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 2559 } else { 2560 Log.v(TAG, " null"); 2561 } 2562 } 2563 if (ai == null) { 2564 // This previously registered preferred activity 2565 // component is no longer known. Most likely an update 2566 // to the app was installed and in the new version this 2567 // component no longer exists. Clean it up by removing 2568 // it from the preferred activities list, and skip it. 2569 Slog.w(TAG, "Removing dangling preferred activity: " 2570 + pa.mPref.mComponent); 2571 mSettings.mPreferredActivities.removeFilter(pa); 2572 continue; 2573 } 2574 for (int j=0; j<N; j++) { 2575 final ResolveInfo ri = query.get(j); 2576 if (!ri.activityInfo.applicationInfo.packageName 2577 .equals(ai.applicationInfo.packageName)) { 2578 continue; 2579 } 2580 if (!ri.activityInfo.name.equals(ai.name)) { 2581 continue; 2582 } 2583 2584 // Okay we found a previously set preferred app. 2585 // If the result set is different from when this 2586 // was created, we need to clear it and re-ask the 2587 // user their preference. 2588 if (!pa.mPref.sameSet(query, priority)) { 2589 Slog.i(TAG, "Result set changed, dropping preferred activity for " 2590 + intent + " type " + resolvedType); 2591 mSettings.mPreferredActivities.removeFilter(pa); 2592 return null; 2593 } 2594 2595 // Yay! 2596 return ri; 2597 } 2598 } 2599 } 2600 } 2601 return null; 2602 } 2603 2604 @Override 2605 public List<ResolveInfo> queryIntentActivities(Intent intent, 2606 String resolvedType, int flags, int userId) { 2607 if (!sUserManager.exists(userId)) return null; 2608 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities"); 2609 ComponentName comp = intent.getComponent(); 2610 if (comp == null) { 2611 if (intent.getSelector() != null) { 2612 intent = intent.getSelector(); 2613 comp = intent.getComponent(); 2614 } 2615 } 2616 2617 if (comp != null) { 2618 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 2619 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 2620 if (ai != null) { 2621 final ResolveInfo ri = new ResolveInfo(); 2622 ri.activityInfo = ai; 2623 list.add(ri); 2624 } 2625 return list; 2626 } 2627 2628 // reader 2629 synchronized (mPackages) { 2630 final String pkgName = intent.getPackage(); 2631 if (pkgName == null) { 2632 return mActivities.queryIntent(intent, resolvedType, flags, userId); 2633 } 2634 final PackageParser.Package pkg = mPackages.get(pkgName); 2635 if (pkg != null) { 2636 return mActivities.queryIntentForPackage(intent, resolvedType, flags, 2637 pkg.activities, userId); 2638 } 2639 return new ArrayList<ResolveInfo>(); 2640 } 2641 } 2642 2643 @Override 2644 public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 2645 Intent[] specifics, String[] specificTypes, Intent intent, 2646 String resolvedType, int flags, int userId) { 2647 if (!sUserManager.exists(userId)) return null; 2648 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, 2649 "query intent activity options"); 2650 final String resultsAction = intent.getAction(); 2651 2652 List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags 2653 | PackageManager.GET_RESOLVED_FILTER, userId); 2654 2655 if (DEBUG_INTENT_MATCHING) { 2656 Log.v(TAG, "Query " + intent + ": " + results); 2657 } 2658 2659 int specificsPos = 0; 2660 int N; 2661 2662 // todo: note that the algorithm used here is O(N^2). This 2663 // isn't a problem in our current environment, but if we start running 2664 // into situations where we have more than 5 or 10 matches then this 2665 // should probably be changed to something smarter... 2666 2667 // First we go through and resolve each of the specific items 2668 // that were supplied, taking care of removing any corresponding 2669 // duplicate items in the generic resolve list. 2670 if (specifics != null) { 2671 for (int i=0; i<specifics.length; i++) { 2672 final Intent sintent = specifics[i]; 2673 if (sintent == null) { 2674 continue; 2675 } 2676 2677 if (DEBUG_INTENT_MATCHING) { 2678 Log.v(TAG, "Specific #" + i + ": " + sintent); 2679 } 2680 2681 String action = sintent.getAction(); 2682 if (resultsAction != null && resultsAction.equals(action)) { 2683 // If this action was explicitly requested, then don't 2684 // remove things that have it. 2685 action = null; 2686 } 2687 2688 ResolveInfo ri = null; 2689 ActivityInfo ai = null; 2690 2691 ComponentName comp = sintent.getComponent(); 2692 if (comp == null) { 2693 ri = resolveIntent( 2694 sintent, 2695 specificTypes != null ? specificTypes[i] : null, 2696 flags, userId); 2697 if (ri == null) { 2698 continue; 2699 } 2700 if (ri == mResolveInfo) { 2701 // ACK! Must do something better with this. 2702 } 2703 ai = ri.activityInfo; 2704 comp = new ComponentName(ai.applicationInfo.packageName, 2705 ai.name); 2706 } else { 2707 ai = getActivityInfo(comp, flags, userId); 2708 if (ai == null) { 2709 continue; 2710 } 2711 } 2712 2713 // Look for any generic query activities that are duplicates 2714 // of this specific one, and remove them from the results. 2715 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 2716 N = results.size(); 2717 int j; 2718 for (j=specificsPos; j<N; j++) { 2719 ResolveInfo sri = results.get(j); 2720 if ((sri.activityInfo.name.equals(comp.getClassName()) 2721 && sri.activityInfo.applicationInfo.packageName.equals( 2722 comp.getPackageName())) 2723 || (action != null && sri.filter.matchAction(action))) { 2724 results.remove(j); 2725 if (DEBUG_INTENT_MATCHING) Log.v( 2726 TAG, "Removing duplicate item from " + j 2727 + " due to specific " + specificsPos); 2728 if (ri == null) { 2729 ri = sri; 2730 } 2731 j--; 2732 N--; 2733 } 2734 } 2735 2736 // Add this specific item to its proper place. 2737 if (ri == null) { 2738 ri = new ResolveInfo(); 2739 ri.activityInfo = ai; 2740 } 2741 results.add(specificsPos, ri); 2742 ri.specificIndex = i; 2743 specificsPos++; 2744 } 2745 } 2746 2747 // Now we go through the remaining generic results and remove any 2748 // duplicate actions that are found here. 2749 N = results.size(); 2750 for (int i=specificsPos; i<N-1; i++) { 2751 final ResolveInfo rii = results.get(i); 2752 if (rii.filter == null) { 2753 continue; 2754 } 2755 2756 // Iterate over all of the actions of this result's intent 2757 // filter... typically this should be just one. 2758 final Iterator<String> it = rii.filter.actionsIterator(); 2759 if (it == null) { 2760 continue; 2761 } 2762 while (it.hasNext()) { 2763 final String action = it.next(); 2764 if (resultsAction != null && resultsAction.equals(action)) { 2765 // If this action was explicitly requested, then don't 2766 // remove things that have it. 2767 continue; 2768 } 2769 for (int j=i+1; j<N; j++) { 2770 final ResolveInfo rij = results.get(j); 2771 if (rij.filter != null && rij.filter.hasAction(action)) { 2772 results.remove(j); 2773 if (DEBUG_INTENT_MATCHING) Log.v( 2774 TAG, "Removing duplicate item from " + j 2775 + " due to action " + action + " at " + i); 2776 j--; 2777 N--; 2778 } 2779 } 2780 } 2781 2782 // If the caller didn't request filter information, drop it now 2783 // so we don't have to marshall/unmarshall it. 2784 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 2785 rii.filter = null; 2786 } 2787 } 2788 2789 // Filter out the caller activity if so requested. 2790 if (caller != null) { 2791 N = results.size(); 2792 for (int i=0; i<N; i++) { 2793 ActivityInfo ainfo = results.get(i).activityInfo; 2794 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 2795 && caller.getClassName().equals(ainfo.name)) { 2796 results.remove(i); 2797 break; 2798 } 2799 } 2800 } 2801 2802 // If the caller didn't request filter information, 2803 // drop them now so we don't have to 2804 // marshall/unmarshall it. 2805 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 2806 N = results.size(); 2807 for (int i=0; i<N; i++) { 2808 results.get(i).filter = null; 2809 } 2810 } 2811 2812 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 2813 return results; 2814 } 2815 2816 @Override 2817 public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags, 2818 int userId) { 2819 if (!sUserManager.exists(userId)) return null; 2820 ComponentName comp = intent.getComponent(); 2821 if (comp == null) { 2822 if (intent.getSelector() != null) { 2823 intent = intent.getSelector(); 2824 comp = intent.getComponent(); 2825 } 2826 } 2827 if (comp != null) { 2828 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 2829 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 2830 if (ai != null) { 2831 ResolveInfo ri = new ResolveInfo(); 2832 ri.activityInfo = ai; 2833 list.add(ri); 2834 } 2835 return list; 2836 } 2837 2838 // reader 2839 synchronized (mPackages) { 2840 String pkgName = intent.getPackage(); 2841 if (pkgName == null) { 2842 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 2843 } 2844 final PackageParser.Package pkg = mPackages.get(pkgName); 2845 if (pkg != null) { 2846 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 2847 userId); 2848 } 2849 return null; 2850 } 2851 } 2852 2853 @Override 2854 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 2855 List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId); 2856 if (!sUserManager.exists(userId)) return null; 2857 if (query != null) { 2858 if (query.size() >= 1) { 2859 // If there is more than one service with the same priority, 2860 // just arbitrarily pick the first one. 2861 return query.get(0); 2862 } 2863 } 2864 return null; 2865 } 2866 2867 @Override 2868 public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags, 2869 int userId) { 2870 if (!sUserManager.exists(userId)) return null; 2871 ComponentName comp = intent.getComponent(); 2872 if (comp == null) { 2873 if (intent.getSelector() != null) { 2874 intent = intent.getSelector(); 2875 comp = intent.getComponent(); 2876 } 2877 } 2878 if (comp != null) { 2879 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 2880 final ServiceInfo si = getServiceInfo(comp, flags, userId); 2881 if (si != null) { 2882 final ResolveInfo ri = new ResolveInfo(); 2883 ri.serviceInfo = si; 2884 list.add(ri); 2885 } 2886 return list; 2887 } 2888 2889 // reader 2890 synchronized (mPackages) { 2891 String pkgName = intent.getPackage(); 2892 if (pkgName == null) { 2893 return mServices.queryIntent(intent, resolvedType, flags, userId); 2894 } 2895 final PackageParser.Package pkg = mPackages.get(pkgName); 2896 if (pkg != null) { 2897 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 2898 userId); 2899 } 2900 return null; 2901 } 2902 } 2903 2904 private static final int getContinuationPoint(final String[] keys, final String key) { 2905 final int index; 2906 if (key == null) { 2907 index = 0; 2908 } else { 2909 final int insertPoint = Arrays.binarySearch(keys, key); 2910 if (insertPoint < 0) { 2911 index = -insertPoint; 2912 } else { 2913 index = insertPoint + 1; 2914 } 2915 } 2916 return index; 2917 } 2918 2919 @Override 2920 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, String lastRead, 2921 int userId) { 2922 final ParceledListSlice<PackageInfo> list = new ParceledListSlice<PackageInfo>(); 2923 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 2924 final String[] keys; 2925 2926 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages"); 2927 2928 // writer 2929 synchronized (mPackages) { 2930 if (listUninstalled) { 2931 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]); 2932 } else { 2933 keys = mPackages.keySet().toArray(new String[mPackages.size()]); 2934 } 2935 2936 Arrays.sort(keys); 2937 int i = getContinuationPoint(keys, lastRead); 2938 final int N = keys.length; 2939 2940 while (i < N) { 2941 final String packageName = keys[i++]; 2942 2943 PackageInfo pi = null; 2944 if (listUninstalled) { 2945 final PackageSetting ps = mSettings.mPackages.get(packageName); 2946 if (ps != null) { 2947 pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId); 2948 } 2949 } else { 2950 final PackageParser.Package p = mPackages.get(packageName); 2951 if (p != null) { 2952 pi = generatePackageInfo(p, flags, userId); 2953 } 2954 } 2955 2956 if (pi != null && list.append(pi)) { 2957 break; 2958 } 2959 } 2960 2961 if (i == N) { 2962 list.setLastSlice(true); 2963 } 2964 } 2965 2966 return list; 2967 } 2968 2969 @Override 2970 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, 2971 String lastRead, int userId) { 2972 if (!sUserManager.exists(userId)) return null; 2973 final ParceledListSlice<ApplicationInfo> list = new ParceledListSlice<ApplicationInfo>(); 2974 final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0; 2975 final String[] keys; 2976 2977 // writer 2978 synchronized (mPackages) { 2979 if (listUninstalled) { 2980 keys = mSettings.mPackages.keySet().toArray(new String[mSettings.mPackages.size()]); 2981 } else { 2982 keys = mPackages.keySet().toArray(new String[mPackages.size()]); 2983 } 2984 2985 Arrays.sort(keys); 2986 int i = getContinuationPoint(keys, lastRead); 2987 final int N = keys.length; 2988 2989 while (i < N) { 2990 final String packageName = keys[i++]; 2991 2992 ApplicationInfo ai = null; 2993 final PackageSetting ps = mSettings.mPackages.get(packageName); 2994 if (listUninstalled) { 2995 if (ps != null) { 2996 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 2997 } 2998 } else { 2999 final PackageParser.Package p = mPackages.get(packageName); 3000 if (p != null && ps != null) { 3001 ai = PackageParser.generateApplicationInfo(p, flags, 3002 ps.readUserState(userId), userId); 3003 } 3004 } 3005 3006 if (ai != null && list.append(ai)) { 3007 break; 3008 } 3009 } 3010 3011 if (i == N) { 3012 list.setLastSlice(true); 3013 } 3014 } 3015 3016 return list; 3017 } 3018 3019 public List<ApplicationInfo> getPersistentApplications(int flags) { 3020 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 3021 3022 // reader 3023 synchronized (mPackages) { 3024 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 3025 final int userId = UserHandle.getCallingUserId(); 3026 while (i.hasNext()) { 3027 final PackageParser.Package p = i.next(); 3028 if (p.applicationInfo != null 3029 && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0 3030 && (!mSafeMode || isSystemApp(p))) { 3031 PackageSetting ps = mSettings.mPackages.get(p.packageName); 3032 if (ps != null) { 3033 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 3034 ps.readUserState(userId), userId); 3035 if (ai != null) { 3036 finalList.add(ai); 3037 } 3038 } 3039 } 3040 } 3041 } 3042 3043 return finalList; 3044 } 3045 3046 @Override 3047 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 3048 if (!sUserManager.exists(userId)) return null; 3049 // reader 3050 synchronized (mPackages) { 3051 final PackageParser.Provider provider = mProviders.get(name); 3052 PackageSetting ps = provider != null 3053 ? mSettings.mPackages.get(provider.owner.packageName) 3054 : null; 3055 return ps != null 3056 && mSettings.isEnabledLPr(provider.info, flags, userId) 3057 && (!mSafeMode || (provider.info.applicationInfo.flags 3058 &ApplicationInfo.FLAG_SYSTEM) != 0) 3059 ? PackageParser.generateProviderInfo(provider, flags, 3060 ps.readUserState(userId), userId) 3061 : null; 3062 } 3063 } 3064 3065 /** 3066 * @deprecated 3067 */ 3068 @Deprecated 3069 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 3070 // reader 3071 synchronized (mPackages) { 3072 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProviders.entrySet() 3073 .iterator(); 3074 final int userId = UserHandle.getCallingUserId(); 3075 while (i.hasNext()) { 3076 Map.Entry<String, PackageParser.Provider> entry = i.next(); 3077 PackageParser.Provider p = entry.getValue(); 3078 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3079 3080 if (ps != null && p.syncable 3081 && (!mSafeMode || (p.info.applicationInfo.flags 3082 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 3083 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 3084 ps.readUserState(userId), userId); 3085 if (info != null) { 3086 outNames.add(entry.getKey()); 3087 outInfo.add(info); 3088 } 3089 } 3090 } 3091 } 3092 } 3093 3094 public List<ProviderInfo> queryContentProviders(String processName, 3095 int uid, int flags) { 3096 ArrayList<ProviderInfo> finalList = null; 3097 3098 // reader 3099 synchronized (mPackages) { 3100 final Iterator<PackageParser.Provider> i = mProvidersByComponent.values().iterator(); 3101 final int userId = processName != null ? 3102 UserHandle.getUserId(uid) : UserHandle.getCallingUserId(); 3103 while (i.hasNext()) { 3104 final PackageParser.Provider p = i.next(); 3105 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 3106 if (ps != null && p.info.authority != null 3107 && (processName == null 3108 || (p.info.processName.equals(processName) 3109 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 3110 && mSettings.isEnabledLPr(p.info, flags, userId) 3111 && (!mSafeMode 3112 || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) { 3113 if (finalList == null) { 3114 finalList = new ArrayList<ProviderInfo>(3); 3115 } 3116 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 3117 ps.readUserState(userId), userId); 3118 if (info != null) { 3119 finalList.add(info); 3120 } 3121 } 3122 } 3123 } 3124 3125 if (finalList != null) { 3126 Collections.sort(finalList, mProviderInitOrderSorter); 3127 } 3128 3129 return finalList; 3130 } 3131 3132 public InstrumentationInfo getInstrumentationInfo(ComponentName name, 3133 int flags) { 3134 // reader 3135 synchronized (mPackages) { 3136 final PackageParser.Instrumentation i = mInstrumentation.get(name); 3137 return PackageParser.generateInstrumentationInfo(i, flags); 3138 } 3139 } 3140 3141 public List<InstrumentationInfo> queryInstrumentation(String targetPackage, 3142 int flags) { 3143 ArrayList<InstrumentationInfo> finalList = 3144 new ArrayList<InstrumentationInfo>(); 3145 3146 // reader 3147 synchronized (mPackages) { 3148 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 3149 while (i.hasNext()) { 3150 final PackageParser.Instrumentation p = i.next(); 3151 if (targetPackage == null 3152 || targetPackage.equals(p.info.targetPackage)) { 3153 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 3154 flags); 3155 if (ii != null) { 3156 finalList.add(ii); 3157 } 3158 } 3159 } 3160 } 3161 3162 return finalList; 3163 } 3164 3165 private void scanDirLI(File dir, int flags, int scanMode, long currentTime) { 3166 String[] files = dir.list(); 3167 if (files == null) { 3168 Log.d(TAG, "No files in app dir " + dir); 3169 return; 3170 } 3171 3172 if (DEBUG_PACKAGE_SCANNING) { 3173 Log.d(TAG, "Scanning app dir " + dir); 3174 } 3175 3176 int i; 3177 for (i=0; i<files.length; i++) { 3178 File file = new File(dir, files[i]); 3179 if (!isPackageFilename(files[i])) { 3180 // Ignore entries which are not apk's 3181 continue; 3182 } 3183 PackageParser.Package pkg = scanPackageLI(file, 3184 flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null); 3185 // Don't mess around with apps in system partition. 3186 if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 && 3187 mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) { 3188 // Delete the apk 3189 Slog.w(TAG, "Cleaning up failed install of " + file); 3190 file.delete(); 3191 } 3192 } 3193 } 3194 3195 private static File getSettingsProblemFile() { 3196 File dataDir = Environment.getDataDirectory(); 3197 File systemDir = new File(dataDir, "system"); 3198 File fname = new File(systemDir, "uiderrors.txt"); 3199 return fname; 3200 } 3201 3202 static void reportSettingsProblem(int priority, String msg) { 3203 try { 3204 File fname = getSettingsProblemFile(); 3205 FileOutputStream out = new FileOutputStream(fname, true); 3206 PrintWriter pw = new PrintWriter(out); 3207 SimpleDateFormat formatter = new SimpleDateFormat(); 3208 String dateString = formatter.format(new Date(System.currentTimeMillis())); 3209 pw.println(dateString + ": " + msg); 3210 pw.close(); 3211 FileUtils.setPermissions( 3212 fname.toString(), 3213 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 3214 -1, -1); 3215 } catch (java.io.IOException e) { 3216 } 3217 Slog.println(priority, TAG, msg); 3218 } 3219 3220 private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps, 3221 PackageParser.Package pkg, File srcFile, int parseFlags) { 3222 if (GET_CERTIFICATES) { 3223 if (ps != null 3224 && ps.codePath.equals(srcFile) 3225 && ps.timeStamp == srcFile.lastModified()) { 3226 if (ps.signatures.mSignatures != null 3227 && ps.signatures.mSignatures.length != 0) { 3228 // Optimization: reuse the existing cached certificates 3229 // if the package appears to be unchanged. 3230 pkg.mSignatures = ps.signatures.mSignatures; 3231 return true; 3232 } 3233 3234 Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures. Collecting certs again to recover them."); 3235 } else { 3236 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 3237 } 3238 3239 if (!pp.collectCertificates(pkg, parseFlags)) { 3240 mLastScanError = pp.getParseError(); 3241 return false; 3242 } 3243 } 3244 return true; 3245 } 3246 3247 /* 3248 * Scan a package and return the newly parsed package. 3249 * Returns null in case of errors and the error code is stored in mLastScanError 3250 */ 3251 private PackageParser.Package scanPackageLI(File scanFile, 3252 int parseFlags, int scanMode, long currentTime, UserHandle user) { 3253 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 3254 String scanPath = scanFile.getPath(); 3255 parseFlags |= mDefParseFlags; 3256 PackageParser pp = new PackageParser(scanPath); 3257 pp.setSeparateProcesses(mSeparateProcesses); 3258 pp.setOnlyCoreApps(mOnlyCore); 3259 final PackageParser.Package pkg = pp.parsePackage(scanFile, 3260 scanPath, mMetrics, parseFlags); 3261 if (pkg == null) { 3262 mLastScanError = pp.getParseError(); 3263 return null; 3264 } 3265 PackageSetting ps = null; 3266 PackageSetting updatedPkg; 3267 // reader 3268 synchronized (mPackages) { 3269 // Look to see if we already know about this package. 3270 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 3271 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 3272 // This package has been renamed to its original name. Let's 3273 // use that. 3274 ps = mSettings.peekPackageLPr(oldName); 3275 } 3276 // If there was no original package, see one for the real package name. 3277 if (ps == null) { 3278 ps = mSettings.peekPackageLPr(pkg.packageName); 3279 } 3280 // Check to see if this package could be hiding/updating a system 3281 // package. Must look for it either under the original or real 3282 // package name depending on our state. 3283 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 3284 } 3285 // First check if this is a system package that may involve an update 3286 if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3287 if (ps != null && !ps.codePath.equals(scanFile)) { 3288 // The path has changed from what was last scanned... check the 3289 // version of the new path against what we have stored to determine 3290 // what to do. 3291 if (pkg.mVersionCode < ps.versionCode) { 3292 // The system package has been updated and the code path does not match 3293 // Ignore entry. Skip it. 3294 Log.i(TAG, "Package " + ps.name + " at " + scanFile 3295 + " ignored: updated version " + ps.versionCode 3296 + " better than this " + pkg.mVersionCode); 3297 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3298 return null; 3299 } else { 3300 // The current app on the system partion is better than 3301 // what we have updated to on the data partition; switch 3302 // back to the system partition version. 3303 // At this point, its safely assumed that package installation for 3304 // apps in system partition will go through. If not there won't be a working 3305 // version of the app 3306 // writer 3307 synchronized (mPackages) { 3308 // Just remove the loaded entries from package lists. 3309 mPackages.remove(ps.name); 3310 } 3311 Slog.w(TAG, "Package " + ps.name + " at " + scanFile 3312 + "reverting from " + ps.codePathString 3313 + ": new version " + pkg.mVersionCode 3314 + " better than installed " + ps.versionCode); 3315 3316 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3317 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString); 3318 synchronized (mInstallLock) { 3319 args.cleanUpResourcesLI(); 3320 } 3321 synchronized (mPackages) { 3322 mSettings.enableSystemPackageLPw(ps.name); 3323 } 3324 } 3325 } 3326 } 3327 3328 if (updatedPkg != null) { 3329 // An updated system app will not have the PARSE_IS_SYSTEM flag set 3330 // initially 3331 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 3332 } 3333 // Verify certificates against what was last scanned 3334 if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) { 3335 Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName); 3336 return null; 3337 } 3338 3339 /* 3340 * A new system app appeared, but we already had a non-system one of the 3341 * same name installed earlier. 3342 */ 3343 boolean shouldHideSystemApp = false; 3344 if (updatedPkg == null && ps != null 3345 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 3346 /* 3347 * Check to make sure the signatures match first. If they don't, 3348 * wipe the installed application and its data. 3349 */ 3350 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 3351 != PackageManager.SIGNATURE_MATCH) { 3352 deletePackageLI(pkg.packageName, null, true, 0, null, false); 3353 ps = null; 3354 } else { 3355 /* 3356 * If the newly-added system app is an older version than the 3357 * already installed version, hide it. It will be scanned later 3358 * and re-added like an update. 3359 */ 3360 if (pkg.mVersionCode < ps.versionCode) { 3361 shouldHideSystemApp = true; 3362 } else { 3363 /* 3364 * The newly found system app is a newer version that the 3365 * one previously installed. Simply remove the 3366 * already-installed application and replace it with our own 3367 * while keeping the application data. 3368 */ 3369 Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from " 3370 + ps.codePathString + ": new version " + pkg.mVersionCode 3371 + " better than installed " + ps.versionCode); 3372 InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps), 3373 ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString); 3374 synchronized (mInstallLock) { 3375 args.cleanUpResourcesLI(); 3376 } 3377 } 3378 } 3379 } 3380 3381 // The apk is forward locked (not public) if its code and resources 3382 // are kept in different files. 3383 // TODO grab this value from PackageSettings 3384 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 3385 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 3386 } 3387 3388 String codePath = null; 3389 String resPath = null; 3390 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0) { 3391 if (ps != null && ps.resourcePathString != null) { 3392 resPath = ps.resourcePathString; 3393 } else { 3394 // Should not happen at all. Just log an error. 3395 Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName); 3396 } 3397 } else { 3398 resPath = pkg.mScanPath; 3399 } 3400 codePath = pkg.mScanPath; 3401 // Set application objects path explicitly. 3402 setApplicationInfoPaths(pkg, codePath, resPath); 3403 // Note that we invoke the following method only if we are about to unpack an application 3404 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode 3405 | SCAN_UPDATE_SIGNATURE, currentTime, user); 3406 3407 /* 3408 * If the system app should be overridden by a previously installed 3409 * data, hide the system app now and let the /data/app scan pick it up 3410 * again. 3411 */ 3412 if (shouldHideSystemApp) { 3413 synchronized (mPackages) { 3414 /* 3415 * We have to grant systems permissions before we hide, because 3416 * grantPermissions will assume the package update is trying to 3417 * expand its permissions. 3418 */ 3419 grantPermissionsLPw(pkg, true); 3420 mSettings.disableSystemPackageLPw(pkg.packageName); 3421 } 3422 } 3423 3424 return scannedPkg; 3425 } 3426 3427 private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath, 3428 String destResPath) { 3429 pkg.mPath = pkg.mScanPath = destCodePath; 3430 pkg.applicationInfo.sourceDir = destCodePath; 3431 pkg.applicationInfo.publicSourceDir = destResPath; 3432 } 3433 3434 private static String fixProcessName(String defProcessName, 3435 String processName, int uid) { 3436 if (processName == null) { 3437 return defProcessName; 3438 } 3439 return processName; 3440 } 3441 3442 private boolean verifySignaturesLP(PackageSetting pkgSetting, 3443 PackageParser.Package pkg) { 3444 if (pkgSetting.signatures.mSignatures != null) { 3445 // Already existing package. Make sure signatures match 3446 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) != 3447 PackageManager.SIGNATURE_MATCH) { 3448 Slog.e(TAG, "Package " + pkg.packageName 3449 + " signatures do not match the previously installed version; ignoring!"); 3450 mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 3451 return false; 3452 } 3453 } 3454 // Check for shared user signatures 3455 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 3456 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 3457 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 3458 Slog.e(TAG, "Package " + pkg.packageName 3459 + " has no signatures that match those in shared user " 3460 + pkgSetting.sharedUser.name + "; ignoring!"); 3461 mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 3462 return false; 3463 } 3464 } 3465 return true; 3466 } 3467 3468 /** 3469 * Enforces that only the system UID or root's UID can call a method exposed 3470 * via Binder. 3471 * 3472 * @param message used as message if SecurityException is thrown 3473 * @throws SecurityException if the caller is not system or root 3474 */ 3475 private static final void enforceSystemOrRoot(String message) { 3476 final int uid = Binder.getCallingUid(); 3477 if (uid != Process.SYSTEM_UID && uid != 0) { 3478 throw new SecurityException(message); 3479 } 3480 } 3481 3482 public void performBootDexOpt() { 3483 ArrayList<PackageParser.Package> pkgs = null; 3484 synchronized (mPackages) { 3485 if (mDeferredDexOpt.size() > 0) { 3486 pkgs = new ArrayList<PackageParser.Package>(mDeferredDexOpt); 3487 mDeferredDexOpt.clear(); 3488 } 3489 } 3490 if (pkgs != null) { 3491 for (int i=0; i<pkgs.size(); i++) { 3492 if (!isFirstBoot()) { 3493 try { 3494 ActivityManagerNative.getDefault().showBootMessage( 3495 mContext.getResources().getString( 3496 com.android.internal.R.string.android_upgrading_apk, 3497 i+1, pkgs.size()), true); 3498 } catch (RemoteException e) { 3499 } 3500 } 3501 PackageParser.Package p = pkgs.get(i); 3502 synchronized (mInstallLock) { 3503 if (!p.mDidDexOpt) { 3504 performDexOptLI(p, false, false); 3505 } 3506 } 3507 } 3508 } 3509 } 3510 3511 public boolean performDexOpt(String packageName) { 3512 enforceSystemOrRoot("Only the system can request dexopt be performed"); 3513 3514 if (!mNoDexOpt) { 3515 return false; 3516 } 3517 3518 PackageParser.Package p; 3519 synchronized (mPackages) { 3520 p = mPackages.get(packageName); 3521 if (p == null || p.mDidDexOpt) { 3522 return false; 3523 } 3524 } 3525 synchronized (mInstallLock) { 3526 return performDexOptLI(p, false, false) == DEX_OPT_PERFORMED; 3527 } 3528 } 3529 3530 static final int DEX_OPT_SKIPPED = 0; 3531 static final int DEX_OPT_PERFORMED = 1; 3532 static final int DEX_OPT_DEFERRED = 2; 3533 static final int DEX_OPT_FAILED = -1; 3534 3535 private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer) { 3536 boolean performed = false; 3537 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 3538 String path = pkg.mScanPath; 3539 int ret = 0; 3540 try { 3541 if (forceDex || dalvik.system.DexFile.isDexOptNeeded(path)) { 3542 if (!forceDex && defer) { 3543 mDeferredDexOpt.add(pkg); 3544 return DEX_OPT_DEFERRED; 3545 } else { 3546 Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName); 3547 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 3548 ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg)); 3549 pkg.mDidDexOpt = true; 3550 performed = true; 3551 } 3552 } 3553 } catch (FileNotFoundException e) { 3554 Slog.w(TAG, "Apk not found for dexopt: " + path); 3555 ret = -1; 3556 } catch (IOException e) { 3557 Slog.w(TAG, "IOException reading apk: " + path, e); 3558 ret = -1; 3559 } catch (dalvik.system.StaleDexCacheError e) { 3560 Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e); 3561 ret = -1; 3562 } catch (Exception e) { 3563 Slog.w(TAG, "Exception when doing dexopt : ", e); 3564 ret = -1; 3565 } 3566 if (ret < 0) { 3567 //error from installer 3568 return DEX_OPT_FAILED; 3569 } 3570 } 3571 3572 return performed ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED; 3573 } 3574 3575 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 3576 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 3577 Slog.w(TAG, "Unable to update from " + oldPkg.name 3578 + " to " + newPkg.packageName 3579 + ": old package not in system partition"); 3580 return false; 3581 } else if (mPackages.get(oldPkg.name) != null) { 3582 Slog.w(TAG, "Unable to update from " + oldPkg.name 3583 + " to " + newPkg.packageName 3584 + ": old package still exists"); 3585 return false; 3586 } 3587 return true; 3588 } 3589 3590 File getDataPathForUser(int userId) { 3591 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId); 3592 } 3593 3594 private File getDataPathForPackage(String packageName, int userId) { 3595 /* 3596 * Until we fully support multiple users, return the directory we 3597 * previously would have. The PackageManagerTests will need to be 3598 * revised when this is changed back.. 3599 */ 3600 if (userId == 0) { 3601 return new File(mAppDataDir, packageName); 3602 } else { 3603 return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId 3604 + File.separator + packageName); 3605 } 3606 } 3607 3608 private int createDataDirsLI(String packageName, int uid) { 3609 int[] users = sUserManager.getUserIds(); 3610 int res = mInstaller.install(packageName, uid, uid); 3611 if (res < 0) { 3612 return res; 3613 } 3614 for (int user : users) { 3615 if (user != 0) { 3616 res = mInstaller.createUserData(packageName, 3617 UserHandle.getUid(user, uid), user); 3618 if (res < 0) { 3619 return res; 3620 } 3621 } 3622 } 3623 return res; 3624 } 3625 3626 private int removeDataDirsLI(String packageName) { 3627 int[] users = sUserManager.getUserIds(); 3628 int res = 0; 3629 for (int user : users) { 3630 int resInner = mInstaller.remove(packageName, user); 3631 if (resInner < 0) { 3632 res = resInner; 3633 } 3634 } 3635 3636 final File nativeLibraryFile = new File(mAppLibInstallDir, packageName); 3637 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 3638 if (!nativeLibraryFile.delete()) { 3639 Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath()); 3640 } 3641 3642 return res; 3643 } 3644 3645 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, 3646 int parseFlags, int scanMode, long currentTime, UserHandle user) { 3647 File scanFile = new File(pkg.mScanPath); 3648 if (scanFile == null || pkg.applicationInfo.sourceDir == null || 3649 pkg.applicationInfo.publicSourceDir == null) { 3650 // Bail out. The resource and code paths haven't been set. 3651 Slog.w(TAG, " Code and resource paths haven't been set correctly"); 3652 mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK; 3653 return null; 3654 } 3655 mScanningPath = scanFile; 3656 3657 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 3658 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 3659 } 3660 3661 if (pkg.packageName.equals("android")) { 3662 synchronized (mPackages) { 3663 if (mAndroidApplication != null) { 3664 Slog.w(TAG, "*************************************************"); 3665 Slog.w(TAG, "Core android package being redefined. Skipping."); 3666 Slog.w(TAG, " file=" + mScanningPath); 3667 Slog.w(TAG, "*************************************************"); 3668 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3669 return null; 3670 } 3671 3672 // Set up information for our fall-back user intent resolution 3673 // activity. 3674 mPlatformPackage = pkg; 3675 pkg.mVersionCode = mSdkVersion; 3676 mAndroidApplication = pkg.applicationInfo; 3677 mResolveActivity.applicationInfo = mAndroidApplication; 3678 mResolveActivity.name = ResolverActivity.class.getName(); 3679 mResolveActivity.packageName = mAndroidApplication.packageName; 3680 mResolveActivity.processName = "system:ui"; 3681 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 3682 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 3683 mResolveActivity.theme = com.android.internal.R.style.Theme_Holo_Dialog_Alert; 3684 mResolveActivity.exported = true; 3685 mResolveActivity.enabled = true; 3686 mResolveInfo.activityInfo = mResolveActivity; 3687 mResolveInfo.priority = 0; 3688 mResolveInfo.preferredOrder = 0; 3689 mResolveInfo.match = 0; 3690 mResolveComponentName = new ComponentName( 3691 mAndroidApplication.packageName, mResolveActivity.name); 3692 } 3693 } 3694 3695 if (DEBUG_PACKAGE_SCANNING) { 3696 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 3697 Log.d(TAG, "Scanning package " + pkg.packageName); 3698 } 3699 3700 if (mPackages.containsKey(pkg.packageName) 3701 || mSharedLibraries.containsKey(pkg.packageName)) { 3702 Slog.w(TAG, "Application package " + pkg.packageName 3703 + " already installed. Skipping duplicate."); 3704 mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 3705 return null; 3706 } 3707 3708 // Initialize package source and resource directories 3709 File destCodeFile = new File(pkg.applicationInfo.sourceDir); 3710 File destResourceFile = new File(pkg.applicationInfo.publicSourceDir); 3711 3712 SharedUserSetting suid = null; 3713 PackageSetting pkgSetting = null; 3714 3715 if (!isSystemApp(pkg)) { 3716 // Only system apps can use these features. 3717 pkg.mOriginalPackages = null; 3718 pkg.mRealPackage = null; 3719 pkg.mAdoptPermissions = null; 3720 } 3721 3722 // writer 3723 synchronized (mPackages) { 3724 // Check all shared libraries and map to their actual file path. 3725 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 3726 if (mTmpSharedLibraries == null || 3727 mTmpSharedLibraries.length < mSharedLibraries.size()) { 3728 mTmpSharedLibraries = new String[mSharedLibraries.size()]; 3729 } 3730 int num = 0; 3731 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 3732 for (int i=0; i<N; i++) { 3733 final String file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 3734 if (file == null) { 3735 Slog.e(TAG, "Package " + pkg.packageName 3736 + " requires unavailable shared library " 3737 + pkg.usesLibraries.get(i) + "; failing!"); 3738 mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 3739 return null; 3740 } 3741 mTmpSharedLibraries[num] = file; 3742 num++; 3743 } 3744 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 3745 for (int i=0; i<N; i++) { 3746 final String file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 3747 if (file == null) { 3748 Slog.w(TAG, "Package " + pkg.packageName 3749 + " desires unavailable shared library " 3750 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 3751 } else { 3752 mTmpSharedLibraries[num] = file; 3753 num++; 3754 } 3755 } 3756 if (num > 0) { 3757 pkg.usesLibraryFiles = new String[num]; 3758 System.arraycopy(mTmpSharedLibraries, 0, 3759 pkg.usesLibraryFiles, 0, num); 3760 } 3761 } 3762 3763 if (pkg.mSharedUserId != null) { 3764 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 3765 pkg.applicationInfo.flags, true); 3766 if (suid == null) { 3767 Slog.w(TAG, "Creating application package " + pkg.packageName 3768 + " for shared user failed"); 3769 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 3770 return null; 3771 } 3772 if (DEBUG_PACKAGE_SCANNING) { 3773 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 3774 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 3775 + "): packages=" + suid.packages); 3776 } 3777 } 3778 3779 // Check if we are renaming from an original package name. 3780 PackageSetting origPackage = null; 3781 String realName = null; 3782 if (pkg.mOriginalPackages != null) { 3783 // This package may need to be renamed to a previously 3784 // installed name. Let's check on that... 3785 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 3786 if (pkg.mOriginalPackages.contains(renamed)) { 3787 // This package had originally been installed as the 3788 // original name, and we have already taken care of 3789 // transitioning to the new one. Just update the new 3790 // one to continue using the old name. 3791 realName = pkg.mRealPackage; 3792 if (!pkg.packageName.equals(renamed)) { 3793 // Callers into this function may have already taken 3794 // care of renaming the package; only do it here if 3795 // it is not already done. 3796 pkg.setPackageName(renamed); 3797 } 3798 3799 } else { 3800 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 3801 if ((origPackage = mSettings.peekPackageLPr( 3802 pkg.mOriginalPackages.get(i))) != null) { 3803 // We do have the package already installed under its 3804 // original name... should we use it? 3805 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 3806 // New package is not compatible with original. 3807 origPackage = null; 3808 continue; 3809 } else if (origPackage.sharedUser != null) { 3810 // Make sure uid is compatible between packages. 3811 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 3812 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 3813 + " to " + pkg.packageName + ": old uid " 3814 + origPackage.sharedUser.name 3815 + " differs from " + pkg.mSharedUserId); 3816 origPackage = null; 3817 continue; 3818 } 3819 } else { 3820 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 3821 + pkg.packageName + " to old name " + origPackage.name); 3822 } 3823 break; 3824 } 3825 } 3826 } 3827 } 3828 3829 if (mTransferedPackages.contains(pkg.packageName)) { 3830 Slog.w(TAG, "Package " + pkg.packageName 3831 + " was transferred to another, but its .apk remains"); 3832 } 3833 3834 // Just create the setting, don't add it yet. For already existing packages 3835 // the PkgSetting exists already and doesn't have to be created. 3836 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 3837 destResourceFile, pkg.applicationInfo.nativeLibraryDir, 3838 pkg.applicationInfo.flags, user, false); 3839 if (pkgSetting == null) { 3840 Slog.w(TAG, "Creating application package " + pkg.packageName + " failed"); 3841 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 3842 return null; 3843 } 3844 3845 if (pkgSetting.origPackage != null) { 3846 // If we are first transitioning from an original package, 3847 // fix up the new package's name now. We need to do this after 3848 // looking up the package under its new name, so getPackageLP 3849 // can take care of fiddling things correctly. 3850 pkg.setPackageName(origPackage.name); 3851 3852 // File a report about this. 3853 String msg = "New package " + pkgSetting.realName 3854 + " renamed to replace old package " + pkgSetting.name; 3855 reportSettingsProblem(Log.WARN, msg); 3856 3857 // Make a note of it. 3858 mTransferedPackages.add(origPackage.name); 3859 3860 // No longer need to retain this. 3861 pkgSetting.origPackage = null; 3862 } 3863 3864 if (realName != null) { 3865 // Make a note of it. 3866 mTransferedPackages.add(pkg.packageName); 3867 } 3868 3869 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 3870 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 3871 } 3872 3873 pkg.applicationInfo.uid = pkgSetting.appId; 3874 pkg.mExtras = pkgSetting; 3875 3876 if (!verifySignaturesLP(pkgSetting, pkg)) { 3877 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 3878 return null; 3879 } 3880 // The signature has changed, but this package is in the system 3881 // image... let's recover! 3882 pkgSetting.signatures.mSignatures = pkg.mSignatures; 3883 // However... if this package is part of a shared user, but it 3884 // doesn't match the signature of the shared user, let's fail. 3885 // What this means is that you can't change the signatures 3886 // associated with an overall shared user, which doesn't seem all 3887 // that unreasonable. 3888 if (pkgSetting.sharedUser != null) { 3889 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 3890 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 3891 Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser); 3892 mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 3893 return null; 3894 } 3895 } 3896 // File a report about this. 3897 String msg = "System package " + pkg.packageName 3898 + " signature changed; retaining data."; 3899 reportSettingsProblem(Log.WARN, msg); 3900 } 3901 3902 // Verify that this new package doesn't have any content providers 3903 // that conflict with existing packages. Only do this if the 3904 // package isn't already installed, since we don't want to break 3905 // things that are installed. 3906 if ((scanMode&SCAN_NEW_INSTALL) != 0) { 3907 final int N = pkg.providers.size(); 3908 int i; 3909 for (i=0; i<N; i++) { 3910 PackageParser.Provider p = pkg.providers.get(i); 3911 if (p.info.authority != null) { 3912 String names[] = p.info.authority.split(";"); 3913 for (int j = 0; j < names.length; j++) { 3914 if (mProviders.containsKey(names[j])) { 3915 PackageParser.Provider other = mProviders.get(names[j]); 3916 Slog.w(TAG, "Can't install because provider name " + names[j] + 3917 " (in package " + pkg.applicationInfo.packageName + 3918 ") is already used by " 3919 + ((other != null && other.getComponentName() != null) 3920 ? other.getComponentName().getPackageName() : "?")); 3921 mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 3922 return null; 3923 } 3924 } 3925 } 3926 } 3927 } 3928 3929 if (pkg.mAdoptPermissions != null) { 3930 // This package wants to adopt ownership of permissions from 3931 // another package. 3932 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 3933 final String origName = pkg.mAdoptPermissions.get(i); 3934 final PackageSetting orig = mSettings.peekPackageLPr(origName); 3935 if (orig != null) { 3936 if (verifyPackageUpdateLPr(orig, pkg)) { 3937 Slog.i(TAG, "Adopting permissions from " + origName + " to " 3938 + pkg.packageName); 3939 mSettings.transferPermissionsLPw(origName, pkg.packageName); 3940 } 3941 } 3942 } 3943 } 3944 } 3945 3946 final String pkgName = pkg.packageName; 3947 3948 final long scanFileTime = scanFile.lastModified(); 3949 final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0; 3950 pkg.applicationInfo.processName = fixProcessName( 3951 pkg.applicationInfo.packageName, 3952 pkg.applicationInfo.processName, 3953 pkg.applicationInfo.uid); 3954 3955 File dataPath; 3956 if (mPlatformPackage == pkg) { 3957 // The system package is special. 3958 dataPath = new File (Environment.getDataDirectory(), "system"); 3959 pkg.applicationInfo.dataDir = dataPath.getPath(); 3960 } else { 3961 // This is a normal package, need to make its data directory. 3962 dataPath = getDataPathForPackage(pkg.packageName, 0); 3963 3964 boolean uidError = false; 3965 3966 if (dataPath.exists()) { 3967 int currentUid = 0; 3968 try { 3969 StructStat stat = Libcore.os.stat(dataPath.getPath()); 3970 currentUid = stat.st_uid; 3971 } catch (ErrnoException e) { 3972 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 3973 } 3974 3975 // If we have mismatched owners for the data path, we have a problem. 3976 if (currentUid != pkg.applicationInfo.uid) { 3977 boolean recovered = false; 3978 if (currentUid == 0) { 3979 // The directory somehow became owned by root. Wow. 3980 // This is probably because the system was stopped while 3981 // installd was in the middle of messing with its libs 3982 // directory. Ask installd to fix that. 3983 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 3984 pkg.applicationInfo.uid); 3985 if (ret >= 0) { 3986 recovered = true; 3987 String msg = "Package " + pkg.packageName 3988 + " unexpectedly changed to uid 0; recovered to " + 3989 + pkg.applicationInfo.uid; 3990 reportSettingsProblem(Log.WARN, msg); 3991 } 3992 } 3993 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 3994 || (scanMode&SCAN_BOOTING) != 0)) { 3995 // If this is a system app, we can at least delete its 3996 // current data so the application will still work. 3997 int ret = removeDataDirsLI(pkgName); 3998 if (ret >= 0) { 3999 // TODO: Kill the processes first 4000 // Old data gone! 4001 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 4002 ? "System package " : "Third party package "; 4003 String msg = prefix + pkg.packageName 4004 + " has changed from uid: " 4005 + currentUid + " to " 4006 + pkg.applicationInfo.uid + "; old data erased"; 4007 reportSettingsProblem(Log.WARN, msg); 4008 recovered = true; 4009 4010 // And now re-install the app. 4011 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid); 4012 if (ret == -1) { 4013 // Ack should not happen! 4014 msg = prefix + pkg.packageName 4015 + " could not have data directory re-created after delete."; 4016 reportSettingsProblem(Log.WARN, msg); 4017 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4018 return null; 4019 } 4020 } 4021 if (!recovered) { 4022 mHasSystemUidErrors = true; 4023 } 4024 } else if (!recovered) { 4025 // If we allow this install to proceed, we will be broken. 4026 // Abort, abort! 4027 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 4028 return null; 4029 } 4030 if (!recovered) { 4031 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 4032 + pkg.applicationInfo.uid + "/fs_" 4033 + currentUid; 4034 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 4035 String msg = "Package " + pkg.packageName 4036 + " has mismatched uid: " 4037 + currentUid + " on disk, " 4038 + pkg.applicationInfo.uid + " in settings"; 4039 // writer 4040 synchronized (mPackages) { 4041 mSettings.mReadMessages.append(msg); 4042 mSettings.mReadMessages.append('\n'); 4043 uidError = true; 4044 if (!pkgSetting.uidError) { 4045 reportSettingsProblem(Log.ERROR, msg); 4046 } 4047 } 4048 } 4049 } 4050 pkg.applicationInfo.dataDir = dataPath.getPath(); 4051 } else { 4052 if (DEBUG_PACKAGE_SCANNING) { 4053 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4054 Log.v(TAG, "Want this data dir: " + dataPath); 4055 } 4056 //invoke installer to do the actual installation 4057 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid); 4058 if (ret < 0) { 4059 // Error from installer 4060 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4061 return null; 4062 } 4063 4064 if (dataPath.exists()) { 4065 pkg.applicationInfo.dataDir = dataPath.getPath(); 4066 } else { 4067 Slog.w(TAG, "Unable to create data directory: " + dataPath); 4068 pkg.applicationInfo.dataDir = null; 4069 } 4070 } 4071 4072 /* 4073 * Set the data dir to the default "/data/data/<package name>/lib" 4074 * if we got here without anyone telling us different (e.g., apps 4075 * stored on SD card have their native libraries stored in the ASEC 4076 * container with the APK). 4077 * 4078 * This happens during an upgrade from a package settings file that 4079 * doesn't have a native library path attribute at all. 4080 */ 4081 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 4082 if (pkgSetting.nativeLibraryPathString == null) { 4083 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4084 } else { 4085 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 4086 } 4087 } 4088 4089 pkgSetting.uidError = uidError; 4090 } 4091 4092 String path = scanFile.getPath(); 4093 /* Note: We don't want to unpack the native binaries for 4094 * system applications, unless they have been updated 4095 * (the binaries are already under /system/lib). 4096 * Also, don't unpack libs for apps on the external card 4097 * since they should have their libraries in the ASEC 4098 * container already. 4099 * 4100 * In other words, we're going to unpack the binaries 4101 * only for non-system apps and system app upgrades. 4102 */ 4103 if (pkg.applicationInfo.nativeLibraryDir != null) { 4104 try { 4105 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 4106 final String dataPathString = dataPath.getCanonicalPath(); 4107 4108 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4109 /* 4110 * Upgrading from a previous version of the OS sometimes 4111 * leaves native libraries in the /data/data/<app>/lib 4112 * directory for system apps even when they shouldn't be. 4113 * Recent changes in the JNI library search path 4114 * necessitates we remove those to match previous behavior. 4115 */ 4116 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 4117 Log.i(TAG, "removed obsolete native libraries for system package " 4118 + path); 4119 } 4120 } else if (!isForwardLocked(pkg) && !isExternal(pkg)) { 4121 // Update native library dir if it starts with /data/data 4122 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 4123 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4124 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 4125 } 4126 4127 try { 4128 if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) { 4129 Slog.e(TAG, "Unable to copy native libraries"); 4130 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4131 return null; 4132 } 4133 } catch (IOException e) { 4134 Slog.e(TAG, "Unable to copy native libraries", e); 4135 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4136 return null; 4137 } 4138 4139 if (mInstaller.linkNativeLibraryDirectory(dataPathString, 4140 pkg.applicationInfo.nativeLibraryDir) == -1) { 4141 Slog.e(TAG, "Unable to link native library directory"); 4142 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4143 return null; 4144 } 4145 } else { 4146 Slog.i(TAG, "Linking native library dir for " + path); 4147 int ret = mInstaller.linkNativeLibraryDirectory(dataPathString, 4148 pkg.applicationInfo.nativeLibraryDir); 4149 if (ret < 0) { 4150 Slog.w(TAG, "Failed linking native library dir for " + path); 4151 mLastScanError = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 4152 return null; 4153 } 4154 } 4155 } catch (IOException ioe) { 4156 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 4157 } 4158 } 4159 pkg.mScanPath = path; 4160 4161 if ((scanMode&SCAN_NO_DEX) == 0) { 4162 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0) 4163 == DEX_OPT_FAILED) { 4164 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 4165 return null; 4166 } 4167 } 4168 4169 if (mFactoryTest && pkg.requestedPermissions.contains( 4170 android.Manifest.permission.FACTORY_TEST)) { 4171 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 4172 } 4173 4174 // Request the ActivityManager to kill the process(only for existing packages) 4175 // so that we do not end up in a confused state while the user is still using the older 4176 // version of the application while the new one gets installed. 4177 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 4178 killApplication(pkg.applicationInfo.packageName, 4179 pkg.applicationInfo.uid); 4180 } 4181 4182 // writer 4183 synchronized (mPackages) { 4184 // We don't expect installation to fail beyond this point, 4185 if ((scanMode&SCAN_MONITOR) != 0) { 4186 mAppDirs.put(pkg.mPath, pkg); 4187 } 4188 // Add the new setting to mSettings 4189 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 4190 // Add the new setting to mPackages 4191 mPackages.put(pkg.applicationInfo.packageName, pkg); 4192 // Make sure we don't accidentally delete its data. 4193 for (int i=0; i<mSettings.mPackagesToBeCleaned.size(); i++) { 4194 mSettings.mPackagesToBeCleaned.valueAt(i).remove(pkgName); 4195 } 4196 4197 // Take care of first install / last update times. 4198 if (currentTime != 0) { 4199 if (pkgSetting.firstInstallTime == 0) { 4200 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 4201 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 4202 pkgSetting.lastUpdateTime = currentTime; 4203 } 4204 } else if (pkgSetting.firstInstallTime == 0) { 4205 // We need *something*. Take time time stamp of the file. 4206 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 4207 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 4208 if (scanFileTime != pkgSetting.timeStamp) { 4209 // A package on the system image has changed; consider this 4210 // to be an update. 4211 pkgSetting.lastUpdateTime = scanFileTime; 4212 } 4213 } 4214 4215 int N = pkg.providers.size(); 4216 StringBuilder r = null; 4217 int i; 4218 for (i=0; i<N; i++) { 4219 PackageParser.Provider p = pkg.providers.get(i); 4220 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 4221 p.info.processName, pkg.applicationInfo.uid); 4222 mProvidersByComponent.put(new ComponentName(p.info.packageName, 4223 p.info.name), p); 4224 p.syncable = p.info.isSyncable; 4225 if (p.info.authority != null) { 4226 String names[] = p.info.authority.split(";"); 4227 p.info.authority = null; 4228 for (int j = 0; j < names.length; j++) { 4229 if (j == 1 && p.syncable) { 4230 // We only want the first authority for a provider to possibly be 4231 // syncable, so if we already added this provider using a different 4232 // authority clear the syncable flag. We copy the provider before 4233 // changing it because the mProviders object contains a reference 4234 // to a provider that we don't want to change. 4235 // Only do this for the second authority since the resulting provider 4236 // object can be the same for all future authorities for this provider. 4237 p = new PackageParser.Provider(p); 4238 p.syncable = false; 4239 } 4240 if (!mProviders.containsKey(names[j])) { 4241 mProviders.put(names[j], p); 4242 if (p.info.authority == null) { 4243 p.info.authority = names[j]; 4244 } else { 4245 p.info.authority = p.info.authority + ";" + names[j]; 4246 } 4247 if (DEBUG_PACKAGE_SCANNING) { 4248 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4249 Log.d(TAG, "Registered content provider: " + names[j] 4250 + ", className = " + p.info.name + ", isSyncable = " 4251 + p.info.isSyncable); 4252 } 4253 } else { 4254 PackageParser.Provider other = mProviders.get(names[j]); 4255 Slog.w(TAG, "Skipping provider name " + names[j] + 4256 " (in package " + pkg.applicationInfo.packageName + 4257 "): name already used by " 4258 + ((other != null && other.getComponentName() != null) 4259 ? other.getComponentName().getPackageName() : "?")); 4260 } 4261 } 4262 } 4263 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4264 if (r == null) { 4265 r = new StringBuilder(256); 4266 } else { 4267 r.append(' '); 4268 } 4269 r.append(p.info.name); 4270 } 4271 } 4272 if (r != null) { 4273 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 4274 } 4275 4276 N = pkg.services.size(); 4277 r = null; 4278 for (i=0; i<N; i++) { 4279 PackageParser.Service s = pkg.services.get(i); 4280 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 4281 s.info.processName, pkg.applicationInfo.uid); 4282 mServices.addService(s); 4283 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4284 if (r == null) { 4285 r = new StringBuilder(256); 4286 } else { 4287 r.append(' '); 4288 } 4289 r.append(s.info.name); 4290 } 4291 } 4292 if (r != null) { 4293 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 4294 } 4295 4296 N = pkg.receivers.size(); 4297 r = null; 4298 for (i=0; i<N; i++) { 4299 PackageParser.Activity a = pkg.receivers.get(i); 4300 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4301 a.info.processName, pkg.applicationInfo.uid); 4302 mReceivers.addActivity(a, "receiver"); 4303 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4304 if (r == null) { 4305 r = new StringBuilder(256); 4306 } else { 4307 r.append(' '); 4308 } 4309 r.append(a.info.name); 4310 } 4311 } 4312 if (r != null) { 4313 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 4314 } 4315 4316 N = pkg.activities.size(); 4317 r = null; 4318 for (i=0; i<N; i++) { 4319 PackageParser.Activity a = pkg.activities.get(i); 4320 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4321 a.info.processName, pkg.applicationInfo.uid); 4322 mActivities.addActivity(a, "activity"); 4323 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4324 if (r == null) { 4325 r = new StringBuilder(256); 4326 } else { 4327 r.append(' '); 4328 } 4329 r.append(a.info.name); 4330 } 4331 } 4332 if (r != null) { 4333 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 4334 } 4335 4336 N = pkg.permissionGroups.size(); 4337 r = null; 4338 for (i=0; i<N; i++) { 4339 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 4340 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 4341 if (cur == null) { 4342 mPermissionGroups.put(pg.info.name, pg); 4343 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4344 if (r == null) { 4345 r = new StringBuilder(256); 4346 } else { 4347 r.append(' '); 4348 } 4349 r.append(pg.info.name); 4350 } 4351 } else { 4352 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 4353 + pg.info.packageName + " ignored: original from " 4354 + cur.info.packageName); 4355 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4356 if (r == null) { 4357 r = new StringBuilder(256); 4358 } else { 4359 r.append(' '); 4360 } 4361 r.append("DUP:"); 4362 r.append(pg.info.name); 4363 } 4364 } 4365 } 4366 if (r != null) { 4367 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 4368 } 4369 4370 N = pkg.permissions.size(); 4371 r = null; 4372 for (i=0; i<N; i++) { 4373 PackageParser.Permission p = pkg.permissions.get(i); 4374 HashMap<String, BasePermission> permissionMap = 4375 p.tree ? mSettings.mPermissionTrees 4376 : mSettings.mPermissions; 4377 p.group = mPermissionGroups.get(p.info.group); 4378 if (p.info.group == null || p.group != null) { 4379 BasePermission bp = permissionMap.get(p.info.name); 4380 if (bp == null) { 4381 bp = new BasePermission(p.info.name, p.info.packageName, 4382 BasePermission.TYPE_NORMAL); 4383 permissionMap.put(p.info.name, bp); 4384 } 4385 if (bp.perm == null) { 4386 if (bp.sourcePackage == null 4387 || bp.sourcePackage.equals(p.info.packageName)) { 4388 BasePermission tree = findPermissionTreeLP(p.info.name); 4389 if (tree == null 4390 || tree.sourcePackage.equals(p.info.packageName)) { 4391 bp.packageSetting = pkgSetting; 4392 bp.perm = p; 4393 bp.uid = pkg.applicationInfo.uid; 4394 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4395 if (r == null) { 4396 r = new StringBuilder(256); 4397 } else { 4398 r.append(' '); 4399 } 4400 r.append(p.info.name); 4401 } 4402 } else { 4403 Slog.w(TAG, "Permission " + p.info.name + " from package " 4404 + p.info.packageName + " ignored: base tree " 4405 + tree.name + " is from package " 4406 + tree.sourcePackage); 4407 } 4408 } else { 4409 Slog.w(TAG, "Permission " + p.info.name + " from package " 4410 + p.info.packageName + " ignored: original from " 4411 + bp.sourcePackage); 4412 } 4413 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4414 if (r == null) { 4415 r = new StringBuilder(256); 4416 } else { 4417 r.append(' '); 4418 } 4419 r.append("DUP:"); 4420 r.append(p.info.name); 4421 } 4422 if (bp.perm == p) { 4423 bp.protectionLevel = p.info.protectionLevel; 4424 } 4425 } else { 4426 Slog.w(TAG, "Permission " + p.info.name + " from package " 4427 + p.info.packageName + " ignored: no group " 4428 + p.group); 4429 } 4430 } 4431 if (r != null) { 4432 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 4433 } 4434 4435 N = pkg.instrumentation.size(); 4436 r = null; 4437 for (i=0; i<N; i++) { 4438 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 4439 a.info.packageName = pkg.applicationInfo.packageName; 4440 a.info.sourceDir = pkg.applicationInfo.sourceDir; 4441 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 4442 a.info.dataDir = pkg.applicationInfo.dataDir; 4443 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 4444 mInstrumentation.put(a.getComponentName(), a); 4445 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4446 if (r == null) { 4447 r = new StringBuilder(256); 4448 } else { 4449 r.append(' '); 4450 } 4451 r.append(a.info.name); 4452 } 4453 } 4454 if (r != null) { 4455 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 4456 } 4457 4458 if (pkg.protectedBroadcasts != null) { 4459 N = pkg.protectedBroadcasts.size(); 4460 for (i=0; i<N; i++) { 4461 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 4462 } 4463 } 4464 4465 pkgSetting.setTimeStamp(scanFileTime); 4466 } 4467 4468 return pkg; 4469 } 4470 4471 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 4472 PackageSetting pkgSetting) { 4473 final String apkLibPath = getApkName(pkgSetting.codePathString); 4474 final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath(); 4475 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 4476 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 4477 } 4478 4479 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 4480 throws IOException { 4481 if (!nativeLibraryDir.isDirectory()) { 4482 nativeLibraryDir.delete(); 4483 4484 if (!nativeLibraryDir.mkdir()) { 4485 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 4486 } 4487 4488 try { 4489 Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH 4490 | S_IXOTH); 4491 } catch (ErrnoException e) { 4492 throw new IOException("Cannot chmod native library directory " 4493 + nativeLibraryDir.getPath(), e); 4494 } 4495 } else if (!SELinux.restorecon(nativeLibraryDir)) { 4496 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 4497 } 4498 4499 /* 4500 * If this is an internal application or our nativeLibraryPath points to 4501 * the app-lib directory, unpack the libraries if necessary. 4502 */ 4503 return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir); 4504 } 4505 4506 private void killApplication(String pkgName, int appId) { 4507 // Request the ActivityManager to kill the process(only for existing packages) 4508 // so that we do not end up in a confused state while the user is still using the older 4509 // version of the application while the new one gets installed. 4510 IActivityManager am = ActivityManagerNative.getDefault(); 4511 if (am != null) { 4512 try { 4513 am.killApplicationWithAppId(pkgName, appId); 4514 } catch (RemoteException e) { 4515 } 4516 } 4517 } 4518 4519 void removePackageLI(PackageSetting ps, boolean chatty) { 4520 if (DEBUG_INSTALL) { 4521 if (chatty) 4522 Log.d(TAG, "Removing package " + ps.name); 4523 } 4524 4525 // writer 4526 synchronized (mPackages) { 4527 mPackages.remove(ps.name); 4528 if (ps.codePathString != null) { 4529 mAppDirs.remove(ps.codePathString); 4530 } 4531 4532 final PackageParser.Package pkg = ps.pkg; 4533 if (pkg != null) { 4534 cleanPackageDataStructuresLILPw(pkg, chatty); 4535 } 4536 } 4537 } 4538 4539 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 4540 if (DEBUG_INSTALL) { 4541 if (chatty) 4542 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 4543 } 4544 4545 // writer 4546 synchronized (mPackages) { 4547 mPackages.remove(pkg.applicationInfo.packageName); 4548 if (pkg.mPath != null) { 4549 mAppDirs.remove(pkg.mPath); 4550 } 4551 cleanPackageDataStructuresLILPw(pkg, chatty); 4552 } 4553 } 4554 4555 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 4556 int N = pkg.providers.size(); 4557 StringBuilder r = null; 4558 int i; 4559 for (i=0; i<N; i++) { 4560 PackageParser.Provider p = pkg.providers.get(i); 4561 mProvidersByComponent.remove(new ComponentName(p.info.packageName, 4562 p.info.name)); 4563 if (p.info.authority == null) { 4564 4565 /* There was another ContentProvider with this authority when 4566 * this app was installed so this authority is null, 4567 * Ignore it as we don't have to unregister the provider. 4568 */ 4569 continue; 4570 } 4571 String names[] = p.info.authority.split(";"); 4572 for (int j = 0; j < names.length; j++) { 4573 if (mProviders.get(names[j]) == p) { 4574 mProviders.remove(names[j]); 4575 if (DEBUG_REMOVE) { 4576 if (chatty) 4577 Log.d(TAG, "Unregistered content provider: " + names[j] 4578 + ", className = " + p.info.name + ", isSyncable = " 4579 + p.info.isSyncable); 4580 } 4581 } 4582 } 4583 if (chatty) { 4584 if (r == null) { 4585 r = new StringBuilder(256); 4586 } else { 4587 r.append(' '); 4588 } 4589 r.append(p.info.name); 4590 } 4591 } 4592 if (r != null) { 4593 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 4594 } 4595 4596 N = pkg.services.size(); 4597 r = null; 4598 for (i=0; i<N; i++) { 4599 PackageParser.Service s = pkg.services.get(i); 4600 mServices.removeService(s); 4601 if (chatty) { 4602 if (r == null) { 4603 r = new StringBuilder(256); 4604 } else { 4605 r.append(' '); 4606 } 4607 r.append(s.info.name); 4608 } 4609 } 4610 if (r != null) { 4611 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 4612 } 4613 4614 N = pkg.receivers.size(); 4615 r = null; 4616 for (i=0; i<N; i++) { 4617 PackageParser.Activity a = pkg.receivers.get(i); 4618 mReceivers.removeActivity(a, "receiver"); 4619 if (chatty) { 4620 if (r == null) { 4621 r = new StringBuilder(256); 4622 } else { 4623 r.append(' '); 4624 } 4625 r.append(a.info.name); 4626 } 4627 } 4628 if (r != null) { 4629 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 4630 } 4631 4632 N = pkg.activities.size(); 4633 r = null; 4634 for (i=0; i<N; i++) { 4635 PackageParser.Activity a = pkg.activities.get(i); 4636 mActivities.removeActivity(a, "activity"); 4637 if (chatty) { 4638 if (r == null) { 4639 r = new StringBuilder(256); 4640 } else { 4641 r.append(' '); 4642 } 4643 r.append(a.info.name); 4644 } 4645 } 4646 if (r != null) { 4647 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 4648 } 4649 4650 N = pkg.permissions.size(); 4651 r = null; 4652 for (i=0; i<N; i++) { 4653 PackageParser.Permission p = pkg.permissions.get(i); 4654 BasePermission bp = mSettings.mPermissions.get(p.info.name); 4655 if (bp == null) { 4656 bp = mSettings.mPermissionTrees.get(p.info.name); 4657 } 4658 if (bp != null && bp.perm == p) { 4659 bp.perm = null; 4660 if (chatty) { 4661 if (r == null) { 4662 r = new StringBuilder(256); 4663 } else { 4664 r.append(' '); 4665 } 4666 r.append(p.info.name); 4667 } 4668 } 4669 } 4670 if (r != null) { 4671 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 4672 } 4673 4674 N = pkg.instrumentation.size(); 4675 r = null; 4676 for (i=0; i<N; i++) { 4677 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 4678 mInstrumentation.remove(a.getComponentName()); 4679 if (chatty) { 4680 if (r == null) { 4681 r = new StringBuilder(256); 4682 } else { 4683 r.append(' '); 4684 } 4685 r.append(a.info.name); 4686 } 4687 } 4688 if (r != null) { 4689 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 4690 } 4691 } 4692 4693 private static final boolean isPackageFilename(String name) { 4694 return name != null && name.endsWith(".apk"); 4695 } 4696 4697 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 4698 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 4699 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 4700 return true; 4701 } 4702 } 4703 return false; 4704 } 4705 4706 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 4707 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 4708 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 4709 4710 private void updatePermissionsLPw(String changingPkg, 4711 PackageParser.Package pkgInfo, int flags) { 4712 // Make sure there are no dangling permission trees. 4713 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 4714 while (it.hasNext()) { 4715 final BasePermission bp = it.next(); 4716 if (bp.packageSetting == null) { 4717 // We may not yet have parsed the package, so just see if 4718 // we still know about its settings. 4719 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 4720 } 4721 if (bp.packageSetting == null) { 4722 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 4723 + " from package " + bp.sourcePackage); 4724 it.remove(); 4725 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 4726 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 4727 Slog.i(TAG, "Removing old permission tree: " + bp.name 4728 + " from package " + bp.sourcePackage); 4729 flags |= UPDATE_PERMISSIONS_ALL; 4730 it.remove(); 4731 } 4732 } 4733 } 4734 4735 // Make sure all dynamic permissions have been assigned to a package, 4736 // and make sure there are no dangling permissions. 4737 it = mSettings.mPermissions.values().iterator(); 4738 while (it.hasNext()) { 4739 final BasePermission bp = it.next(); 4740 if (bp.type == BasePermission.TYPE_DYNAMIC) { 4741 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 4742 + bp.name + " pkg=" + bp.sourcePackage 4743 + " info=" + bp.pendingInfo); 4744 if (bp.packageSetting == null && bp.pendingInfo != null) { 4745 final BasePermission tree = findPermissionTreeLP(bp.name); 4746 if (tree != null && tree.perm != null) { 4747 bp.packageSetting = tree.packageSetting; 4748 bp.perm = new PackageParser.Permission(tree.perm.owner, 4749 new PermissionInfo(bp.pendingInfo)); 4750 bp.perm.info.packageName = tree.perm.info.packageName; 4751 bp.perm.info.name = bp.name; 4752 bp.uid = tree.uid; 4753 } 4754 } 4755 } 4756 if (bp.packageSetting == null) { 4757 // We may not yet have parsed the package, so just see if 4758 // we still know about its settings. 4759 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 4760 } 4761 if (bp.packageSetting == null) { 4762 Slog.w(TAG, "Removing dangling permission: " + bp.name 4763 + " from package " + bp.sourcePackage); 4764 it.remove(); 4765 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 4766 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 4767 Slog.i(TAG, "Removing old permission: " + bp.name 4768 + " from package " + bp.sourcePackage); 4769 flags |= UPDATE_PERMISSIONS_ALL; 4770 it.remove(); 4771 } 4772 } 4773 } 4774 4775 // Now update the permissions for all packages, in particular 4776 // replace the granted permissions of the system packages. 4777 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 4778 for (PackageParser.Package pkg : mPackages.values()) { 4779 if (pkg != pkgInfo) { 4780 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 4781 } 4782 } 4783 } 4784 4785 if (pkgInfo != null) { 4786 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 4787 } 4788 } 4789 4790 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 4791 final PackageSetting ps = (PackageSetting) pkg.mExtras; 4792 if (ps == null) { 4793 return; 4794 } 4795 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 4796 HashSet<String> origPermissions = gp.grantedPermissions; 4797 boolean changedPermission = false; 4798 4799 if (replace) { 4800 ps.permissionsFixed = false; 4801 if (gp == ps) { 4802 origPermissions = new HashSet<String>(gp.grantedPermissions); 4803 gp.grantedPermissions.clear(); 4804 gp.gids = mGlobalGids; 4805 } 4806 } 4807 4808 if (gp.gids == null) { 4809 gp.gids = mGlobalGids; 4810 } 4811 4812 final int N = pkg.requestedPermissions.size(); 4813 for (int i=0; i<N; i++) { 4814 final String name = pkg.requestedPermissions.get(i); 4815 //final boolean required = pkg.requestedPermssionsRequired.get(i); 4816 final BasePermission bp = mSettings.mPermissions.get(name); 4817 if (DEBUG_INSTALL) { 4818 if (gp != ps) { 4819 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 4820 } 4821 } 4822 if (bp != null && bp.packageSetting != null) { 4823 final String perm = bp.name; 4824 boolean allowed; 4825 boolean allowedSig = false; 4826 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 4827 if (level == PermissionInfo.PROTECTION_NORMAL 4828 || level == PermissionInfo.PROTECTION_DANGEROUS) { 4829 allowed = true; 4830 } else if (bp.packageSetting == null) { 4831 // This permission is invalid; skip it. 4832 allowed = false; 4833 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 4834 allowed = (compareSignatures( 4835 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 4836 == PackageManager.SIGNATURE_MATCH) 4837 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 4838 == PackageManager.SIGNATURE_MATCH); 4839 if (!allowed && (bp.protectionLevel 4840 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 4841 if (isSystemApp(pkg)) { 4842 // For updated system applications, a system permission 4843 // is granted only if it had been defined by the original application. 4844 if (isUpdatedSystemApp(pkg)) { 4845 final PackageSetting sysPs = mSettings 4846 .getDisabledSystemPkgLPr(pkg.packageName); 4847 final GrantedPermissions origGp = sysPs.sharedUser != null 4848 ? sysPs.sharedUser : sysPs; 4849 if (origGp.grantedPermissions.contains(perm)) { 4850 allowed = true; 4851 } else { 4852 allowed = false; 4853 } 4854 } else { 4855 allowed = true; 4856 } 4857 } 4858 } 4859 if (!allowed && (bp.protectionLevel 4860 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 4861 // For development permissions, a development permission 4862 // is granted only if it was already granted. 4863 if (origPermissions.contains(perm)) { 4864 allowed = true; 4865 } else { 4866 allowed = false; 4867 } 4868 } 4869 if (allowed) { 4870 allowedSig = true; 4871 } 4872 } else { 4873 allowed = false; 4874 } 4875 if (DEBUG_INSTALL) { 4876 if (gp != ps) { 4877 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 4878 } 4879 } 4880 if (allowed) { 4881 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 4882 && ps.permissionsFixed) { 4883 // If this is an existing, non-system package, then 4884 // we can't add any new permissions to it. 4885 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 4886 allowed = false; 4887 // Except... if this is a permission that was added 4888 // to the platform (note: need to only do this when 4889 // updating the platform). 4890 final int NP = PackageParser.NEW_PERMISSIONS.length; 4891 for (int ip=0; ip<NP; ip++) { 4892 final PackageParser.NewPermissionInfo npi 4893 = PackageParser.NEW_PERMISSIONS[ip]; 4894 if (npi.name.equals(perm) 4895 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 4896 allowed = true; 4897 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 4898 + pkg.packageName); 4899 break; 4900 } 4901 } 4902 } 4903 } 4904 if (allowed) { 4905 if (!gp.grantedPermissions.contains(perm)) { 4906 changedPermission = true; 4907 gp.grantedPermissions.add(perm); 4908 gp.gids = appendInts(gp.gids, bp.gids); 4909 } else if (!ps.haveGids) { 4910 gp.gids = appendInts(gp.gids, bp.gids); 4911 } 4912 } else { 4913 Slog.w(TAG, "Not granting permission " + perm 4914 + " to package " + pkg.packageName 4915 + " because it was previously installed without"); 4916 } 4917 } else { 4918 if (gp.grantedPermissions.remove(perm)) { 4919 changedPermission = true; 4920 gp.gids = removeInts(gp.gids, bp.gids); 4921 Slog.i(TAG, "Un-granting permission " + perm 4922 + " from package " + pkg.packageName 4923 + " (protectionLevel=" + bp.protectionLevel 4924 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 4925 + ")"); 4926 } else { 4927 Slog.w(TAG, "Not granting permission " + perm 4928 + " to package " + pkg.packageName 4929 + " (protectionLevel=" + bp.protectionLevel 4930 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 4931 + ")"); 4932 } 4933 } 4934 } else { 4935 Slog.w(TAG, "Unknown permission " + name 4936 + " in package " + pkg.packageName); 4937 } 4938 } 4939 4940 if ((changedPermission || replace) && !ps.permissionsFixed && 4941 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) || 4942 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){ 4943 // This is the first that we have heard about this package, so the 4944 // permissions we have now selected are fixed until explicitly 4945 // changed. 4946 ps.permissionsFixed = true; 4947 } 4948 ps.haveGids = true; 4949 } 4950 4951 private final class ActivityIntentResolver 4952 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 4953 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 4954 boolean defaultOnly, int userId) { 4955 if (!sUserManager.exists(userId)) return null; 4956 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 4957 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 4958 } 4959 4960 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 4961 int userId) { 4962 if (!sUserManager.exists(userId)) return null; 4963 mFlags = flags; 4964 return super.queryIntent(intent, resolvedType, 4965 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 4966 } 4967 4968 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 4969 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 4970 if (!sUserManager.exists(userId)) return null; 4971 if (packageActivities == null) { 4972 return null; 4973 } 4974 mFlags = flags; 4975 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 4976 final int N = packageActivities.size(); 4977 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 4978 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 4979 4980 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 4981 for (int i = 0; i < N; ++i) { 4982 intentFilters = packageActivities.get(i).intents; 4983 if (intentFilters != null && intentFilters.size() > 0) { 4984 PackageParser.ActivityIntentInfo[] array = 4985 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 4986 intentFilters.toArray(array); 4987 listCut.add(array); 4988 } 4989 } 4990 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 4991 } 4992 4993 public final void addActivity(PackageParser.Activity a, String type) { 4994 final boolean systemApp = isSystemApp(a.info.applicationInfo); 4995 mActivities.put(a.getComponentName(), a); 4996 if (DEBUG_SHOW_INFO) 4997 Log.v( 4998 TAG, " " + type + " " + 4999 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 5000 if (DEBUG_SHOW_INFO) 5001 Log.v(TAG, " Class=" + a.info.name); 5002 final int NI = a.intents.size(); 5003 for (int j=0; j<NI; j++) { 5004 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 5005 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 5006 intent.setPriority(0); 5007 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 5008 + a.className + " with priority > 0, forcing to 0"); 5009 } 5010 if (DEBUG_SHOW_INFO) { 5011 Log.v(TAG, " IntentFilter:"); 5012 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5013 } 5014 if (!intent.debugCheck()) { 5015 Log.w(TAG, "==> For Activity " + a.info.name); 5016 } 5017 addFilter(intent); 5018 } 5019 } 5020 5021 public final void removeActivity(PackageParser.Activity a, String type) { 5022 mActivities.remove(a.getComponentName()); 5023 if (DEBUG_SHOW_INFO) { 5024 Log.v(TAG, " " + type + " " 5025 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 5026 : a.info.name) + ":"); 5027 Log.v(TAG, " Class=" + a.info.name); 5028 } 5029 final int NI = a.intents.size(); 5030 for (int j=0; j<NI; j++) { 5031 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 5032 if (DEBUG_SHOW_INFO) { 5033 Log.v(TAG, " IntentFilter:"); 5034 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5035 } 5036 removeFilter(intent); 5037 } 5038 } 5039 5040 @Override 5041 protected boolean allowFilterResult( 5042 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 5043 ActivityInfo filterAi = filter.activity.info; 5044 for (int i=dest.size()-1; i>=0; i--) { 5045 ActivityInfo destAi = dest.get(i).activityInfo; 5046 if (destAi.name == filterAi.name 5047 && destAi.packageName == filterAi.packageName) { 5048 return false; 5049 } 5050 } 5051 return true; 5052 } 5053 5054 @Override 5055 protected ActivityIntentInfo[] newArray(int size) { 5056 return new ActivityIntentInfo[size]; 5057 } 5058 5059 @Override 5060 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 5061 if (!sUserManager.exists(userId)) return true; 5062 PackageParser.Package p = filter.activity.owner; 5063 if (p != null) { 5064 PackageSetting ps = (PackageSetting)p.mExtras; 5065 if (ps != null) { 5066 // System apps are never considered stopped for purposes of 5067 // filtering, because there may be no way for the user to 5068 // actually re-launch them. 5069 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 5070 && ps.getStopped(userId); 5071 } 5072 } 5073 return false; 5074 } 5075 5076 @Override 5077 protected String packageForFilter(PackageParser.ActivityIntentInfo info) { 5078 return info.activity.owner.packageName; 5079 } 5080 5081 @Override 5082 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 5083 int match, int userId) { 5084 if (!sUserManager.exists(userId)) return null; 5085 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 5086 return null; 5087 } 5088 final PackageParser.Activity activity = info.activity; 5089 if (mSafeMode && (activity.info.applicationInfo.flags 5090 &ApplicationInfo.FLAG_SYSTEM) == 0) { 5091 return null; 5092 } 5093 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 5094 if (ps == null) { 5095 return null; 5096 } 5097 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 5098 ps.readUserState(userId), userId); 5099 if (ai == null) { 5100 return null; 5101 } 5102 final ResolveInfo res = new ResolveInfo(); 5103 res.activityInfo = ai; 5104 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 5105 res.filter = info; 5106 } 5107 res.priority = info.getPriority(); 5108 res.preferredOrder = activity.owner.mPreferredOrder; 5109 //System.out.println("Result: " + res.activityInfo.className + 5110 // " = " + res.priority); 5111 res.match = match; 5112 res.isDefault = info.hasDefault; 5113 res.labelRes = info.labelRes; 5114 res.nonLocalizedLabel = info.nonLocalizedLabel; 5115 res.icon = info.icon; 5116 res.system = isSystemApp(res.activityInfo.applicationInfo); 5117 return res; 5118 } 5119 5120 @Override 5121 protected void sortResults(List<ResolveInfo> results) { 5122 Collections.sort(results, mResolvePrioritySorter); 5123 } 5124 5125 @Override 5126 protected void dumpFilter(PrintWriter out, String prefix, 5127 PackageParser.ActivityIntentInfo filter) { 5128 out.print(prefix); out.print( 5129 Integer.toHexString(System.identityHashCode(filter.activity))); 5130 out.print(' '); 5131 out.print(filter.activity.getComponentShortName()); 5132 out.print(" filter "); 5133 out.println(Integer.toHexString(System.identityHashCode(filter))); 5134 } 5135 5136// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 5137// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 5138// final List<ResolveInfo> retList = Lists.newArrayList(); 5139// while (i.hasNext()) { 5140// final ResolveInfo resolveInfo = i.next(); 5141// if (isEnabledLP(resolveInfo.activityInfo)) { 5142// retList.add(resolveInfo); 5143// } 5144// } 5145// return retList; 5146// } 5147 5148 // Keys are String (activity class name), values are Activity. 5149 private final HashMap<ComponentName, PackageParser.Activity> mActivities 5150 = new HashMap<ComponentName, PackageParser.Activity>(); 5151 private int mFlags; 5152 } 5153 5154 private final class ServiceIntentResolver 5155 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 5156 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 5157 boolean defaultOnly, int userId) { 5158 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 5159 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 5160 } 5161 5162 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 5163 int userId) { 5164 if (!sUserManager.exists(userId)) return null; 5165 mFlags = flags; 5166 return super.queryIntent(intent, resolvedType, 5167 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 5168 } 5169 5170 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 5171 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 5172 if (!sUserManager.exists(userId)) return null; 5173 if (packageServices == null) { 5174 return null; 5175 } 5176 mFlags = flags; 5177 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 5178 final int N = packageServices.size(); 5179 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 5180 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 5181 5182 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 5183 for (int i = 0; i < N; ++i) { 5184 intentFilters = packageServices.get(i).intents; 5185 if (intentFilters != null && intentFilters.size() > 0) { 5186 PackageParser.ServiceIntentInfo[] array = 5187 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 5188 intentFilters.toArray(array); 5189 listCut.add(array); 5190 } 5191 } 5192 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 5193 } 5194 5195 public final void addService(PackageParser.Service s) { 5196 mServices.put(s.getComponentName(), s); 5197 if (DEBUG_SHOW_INFO) { 5198 Log.v(TAG, " " 5199 + (s.info.nonLocalizedLabel != null 5200 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 5201 Log.v(TAG, " Class=" + s.info.name); 5202 } 5203 final int NI = s.intents.size(); 5204 int j; 5205 for (j=0; j<NI; j++) { 5206 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 5207 if (DEBUG_SHOW_INFO) { 5208 Log.v(TAG, " IntentFilter:"); 5209 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5210 } 5211 if (!intent.debugCheck()) { 5212 Log.w(TAG, "==> For Service " + s.info.name); 5213 } 5214 addFilter(intent); 5215 } 5216 } 5217 5218 public final void removeService(PackageParser.Service s) { 5219 mServices.remove(s.getComponentName()); 5220 if (DEBUG_SHOW_INFO) { 5221 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 5222 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 5223 Log.v(TAG, " Class=" + s.info.name); 5224 } 5225 final int NI = s.intents.size(); 5226 int j; 5227 for (j=0; j<NI; j++) { 5228 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 5229 if (DEBUG_SHOW_INFO) { 5230 Log.v(TAG, " IntentFilter:"); 5231 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5232 } 5233 removeFilter(intent); 5234 } 5235 } 5236 5237 @Override 5238 protected boolean allowFilterResult( 5239 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 5240 ServiceInfo filterSi = filter.service.info; 5241 for (int i=dest.size()-1; i>=0; i--) { 5242 ServiceInfo destAi = dest.get(i).serviceInfo; 5243 if (destAi.name == filterSi.name 5244 && destAi.packageName == filterSi.packageName) { 5245 return false; 5246 } 5247 } 5248 return true; 5249 } 5250 5251 @Override 5252 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 5253 return new PackageParser.ServiceIntentInfo[size]; 5254 } 5255 5256 @Override 5257 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 5258 if (!sUserManager.exists(userId)) return true; 5259 PackageParser.Package p = filter.service.owner; 5260 if (p != null) { 5261 PackageSetting ps = (PackageSetting)p.mExtras; 5262 if (ps != null) { 5263 // System apps are never considered stopped for purposes of 5264 // filtering, because there may be no way for the user to 5265 // actually re-launch them. 5266 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 5267 && ps.getStopped(userId); 5268 } 5269 } 5270 return false; 5271 } 5272 5273 @Override 5274 protected String packageForFilter(PackageParser.ServiceIntentInfo info) { 5275 return info.service.owner.packageName; 5276 } 5277 5278 @Override 5279 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 5280 int match, int userId) { 5281 if (!sUserManager.exists(userId)) return null; 5282 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 5283 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 5284 return null; 5285 } 5286 final PackageParser.Service service = info.service; 5287 if (mSafeMode && (service.info.applicationInfo.flags 5288 &ApplicationInfo.FLAG_SYSTEM) == 0) { 5289 return null; 5290 } 5291 PackageSetting ps = (PackageSetting) service.owner.mExtras; 5292 if (ps == null) { 5293 return null; 5294 } 5295 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 5296 ps.readUserState(userId), userId); 5297 if (si == null) { 5298 return null; 5299 } 5300 final ResolveInfo res = new ResolveInfo(); 5301 res.serviceInfo = si; 5302 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 5303 res.filter = filter; 5304 } 5305 res.priority = info.getPriority(); 5306 res.preferredOrder = service.owner.mPreferredOrder; 5307 //System.out.println("Result: " + res.activityInfo.className + 5308 // " = " + res.priority); 5309 res.match = match; 5310 res.isDefault = info.hasDefault; 5311 res.labelRes = info.labelRes; 5312 res.nonLocalizedLabel = info.nonLocalizedLabel; 5313 res.icon = info.icon; 5314 res.system = isSystemApp(res.serviceInfo.applicationInfo); 5315 return res; 5316 } 5317 5318 @Override 5319 protected void sortResults(List<ResolveInfo> results) { 5320 Collections.sort(results, mResolvePrioritySorter); 5321 } 5322 5323 @Override 5324 protected void dumpFilter(PrintWriter out, String prefix, 5325 PackageParser.ServiceIntentInfo filter) { 5326 out.print(prefix); out.print( 5327 Integer.toHexString(System.identityHashCode(filter.service))); 5328 out.print(' '); 5329 out.print(filter.service.getComponentShortName()); 5330 out.print(" filter "); 5331 out.println(Integer.toHexString(System.identityHashCode(filter))); 5332 } 5333 5334// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 5335// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 5336// final List<ResolveInfo> retList = Lists.newArrayList(); 5337// while (i.hasNext()) { 5338// final ResolveInfo resolveInfo = (ResolveInfo) i; 5339// if (isEnabledLP(resolveInfo.serviceInfo)) { 5340// retList.add(resolveInfo); 5341// } 5342// } 5343// return retList; 5344// } 5345 5346 // Keys are String (activity class name), values are Activity. 5347 private final HashMap<ComponentName, PackageParser.Service> mServices 5348 = new HashMap<ComponentName, PackageParser.Service>(); 5349 private int mFlags; 5350 }; 5351 5352 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 5353 new Comparator<ResolveInfo>() { 5354 public int compare(ResolveInfo r1, ResolveInfo r2) { 5355 int v1 = r1.priority; 5356 int v2 = r2.priority; 5357 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 5358 if (v1 != v2) { 5359 return (v1 > v2) ? -1 : 1; 5360 } 5361 v1 = r1.preferredOrder; 5362 v2 = r2.preferredOrder; 5363 if (v1 != v2) { 5364 return (v1 > v2) ? -1 : 1; 5365 } 5366 if (r1.isDefault != r2.isDefault) { 5367 return r1.isDefault ? -1 : 1; 5368 } 5369 v1 = r1.match; 5370 v2 = r2.match; 5371 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 5372 if (v1 != v2) { 5373 return (v1 > v2) ? -1 : 1; 5374 } 5375 if (r1.system != r2.system) { 5376 return r1.system ? -1 : 1; 5377 } 5378 return 0; 5379 } 5380 }; 5381 5382 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 5383 new Comparator<ProviderInfo>() { 5384 public int compare(ProviderInfo p1, ProviderInfo p2) { 5385 final int v1 = p1.initOrder; 5386 final int v2 = p2.initOrder; 5387 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 5388 } 5389 }; 5390 5391 static final void sendPackageBroadcast(String action, String pkg, 5392 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 5393 int[] userIds) { 5394 IActivityManager am = ActivityManagerNative.getDefault(); 5395 if (am != null) { 5396 try { 5397 if (userIds == null) { 5398 userIds = am.getRunningUserIds(); 5399 } 5400 for (int id : userIds) { 5401 final Intent intent = new Intent(action, 5402 pkg != null ? Uri.fromParts("package", pkg, null) : null); 5403 if (extras != null) { 5404 intent.putExtras(extras); 5405 } 5406 if (targetPkg != null) { 5407 intent.setPackage(targetPkg); 5408 } 5409 // Modify the UID when posting to other users 5410 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 5411 if (uid > 0 && UserHandle.getUserId(uid) != id) { 5412 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 5413 intent.putExtra(Intent.EXTRA_UID, uid); 5414 } 5415 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 5416 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 5417 if (DEBUG_BROADCASTS) { 5418 RuntimeException here = new RuntimeException("here"); 5419 here.fillInStackTrace(); 5420 Slog.d(TAG, "Sending to user " + id + ": " 5421 + intent.toShortString(false, true, false, false) 5422 + " " + intent.getExtras(), here); 5423 } 5424 am.broadcastIntent(null, intent, null, finishedReceiver, 5425 0, null, null, null, finishedReceiver != null, false, id); 5426 } 5427 } catch (RemoteException ex) { 5428 } 5429 } 5430 } 5431 5432 /** 5433 * Check if the external storage media is available. This is true if there 5434 * is a mounted external storage medium or if the external storage is 5435 * emulated. 5436 */ 5437 private boolean isExternalMediaAvailable() { 5438 return mMediaMounted || Environment.isExternalStorageEmulated(); 5439 } 5440 5441 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 5442 // writer 5443 final int userId = UserHandle.getCallingUserId(); 5444 synchronized (mPackages) { 5445 if (!isExternalMediaAvailable()) { 5446 // If the external storage is no longer mounted at this point, 5447 // the caller may not have been able to delete all of this 5448 // packages files and can not delete any more. Bail. 5449 return null; 5450 } 5451 ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned.get(userId); 5452 if (pkgs != null) { 5453 if (lastPackage != null) { 5454 pkgs.remove(lastPackage); 5455 } 5456 if (pkgs.size() > 0) { 5457 return pkgs.get(0); 5458 } 5459 } 5460 mSettings.mPackagesToBeCleaned.remove(userId); 5461 } 5462 // Move on to the next user to clean. 5463 long ident = Binder.clearCallingIdentity(); 5464 try { 5465 startCleaningPackages(userId); 5466 } finally { 5467 Binder.restoreCallingIdentity(ident); 5468 } 5469 return null; 5470 } 5471 5472 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 5473 if (false) { 5474 RuntimeException here = new RuntimeException("here"); 5475 here.fillInStackTrace(); 5476 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 5477 + " andCode=" + andCode, here); 5478 } 5479 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 5480 userId, andCode ? 1 : 0, packageName)); 5481 } 5482 5483 void startCleaningPackages(int lastUser) { 5484 // reader 5485 int nextUser = -1; 5486 synchronized (mPackages) { 5487 if (!isExternalMediaAvailable()) { 5488 return; 5489 } 5490 final int N = mSettings.mPackagesToBeCleaned.size(); 5491 if (N <= 0) { 5492 return; 5493 } 5494 for (int i=0; i<N; i++) { 5495 int user = mSettings.mPackagesToBeCleaned.keyAt(i); 5496 if (user > lastUser) { 5497 nextUser = user; 5498 break; 5499 } 5500 } 5501 if (nextUser < 0) { 5502 nextUser = mSettings.mPackagesToBeCleaned.keyAt(0); 5503 } 5504 } 5505 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 5506 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 5507 IActivityManager am = ActivityManagerNative.getDefault(); 5508 if (am != null) { 5509 try { 5510 am.startService(null, intent, null, nextUser); 5511 } catch (RemoteException e) { 5512 } 5513 } 5514 } 5515 5516 private final class AppDirObserver extends FileObserver { 5517 public AppDirObserver(String path, int mask, boolean isrom) { 5518 super(path, mask); 5519 mRootDir = path; 5520 mIsRom = isrom; 5521 } 5522 5523 public void onEvent(int event, String path) { 5524 String removedPackage = null; 5525 int removedAppId = -1; 5526 int[] removedUsers = null; 5527 String addedPackage = null; 5528 int addedAppId = -1; 5529 int[] addedUsers = null; 5530 5531 // TODO post a message to the handler to obtain serial ordering 5532 synchronized (mInstallLock) { 5533 String fullPathStr = null; 5534 File fullPath = null; 5535 if (path != null) { 5536 fullPath = new File(mRootDir, path); 5537 fullPathStr = fullPath.getPath(); 5538 } 5539 5540 if (DEBUG_APP_DIR_OBSERVER) 5541 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 5542 5543 if (!isPackageFilename(path)) { 5544 if (DEBUG_APP_DIR_OBSERVER) 5545 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 5546 return; 5547 } 5548 5549 // Ignore packages that are being installed or 5550 // have just been installed. 5551 if (ignoreCodePath(fullPathStr)) { 5552 return; 5553 } 5554 PackageParser.Package p = null; 5555 PackageSetting ps = null; 5556 // reader 5557 synchronized (mPackages) { 5558 p = mAppDirs.get(fullPathStr); 5559 if (p != null) { 5560 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 5561 if (ps != null) { 5562 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 5563 } else { 5564 removedUsers = sUserManager.getUserIds(); 5565 } 5566 } 5567 addedUsers = sUserManager.getUserIds(); 5568 } 5569 if ((event&REMOVE_EVENTS) != 0) { 5570 if (ps != null) { 5571 removePackageLI(ps, true); 5572 removedPackage = ps.name; 5573 removedAppId = ps.appId; 5574 } 5575 } 5576 5577 if ((event&ADD_EVENTS) != 0) { 5578 if (p == null) { 5579 p = scanPackageLI(fullPath, 5580 (mIsRom ? PackageParser.PARSE_IS_SYSTEM 5581 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) | 5582 PackageParser.PARSE_CHATTY | 5583 PackageParser.PARSE_MUST_BE_APK, 5584 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 5585 System.currentTimeMillis(), UserHandle.ALL); 5586 if (p != null) { 5587 /* 5588 * TODO this seems dangerous as the package may have 5589 * changed since we last acquired the mPackages 5590 * lock. 5591 */ 5592 // writer 5593 synchronized (mPackages) { 5594 updatePermissionsLPw(p.packageName, p, 5595 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 5596 } 5597 addedPackage = p.applicationInfo.packageName; 5598 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 5599 } 5600 } 5601 } 5602 5603 // reader 5604 synchronized (mPackages) { 5605 mSettings.writeLPr(); 5606 } 5607 } 5608 5609 if (removedPackage != null) { 5610 Bundle extras = new Bundle(1); 5611 extras.putInt(Intent.EXTRA_UID, removedAppId); 5612 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 5613 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 5614 extras, null, null, removedUsers); 5615 } 5616 if (addedPackage != null) { 5617 Bundle extras = new Bundle(1); 5618 extras.putInt(Intent.EXTRA_UID, addedAppId); 5619 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 5620 extras, null, null, addedUsers); 5621 } 5622 } 5623 5624 private final String mRootDir; 5625 private final boolean mIsRom; 5626 } 5627 5628 /* Called when a downloaded package installation has been confirmed by the user */ 5629 public void installPackage( 5630 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 5631 installPackage(packageURI, observer, flags, null); 5632 } 5633 5634 /* Called when a downloaded package installation has been confirmed by the user */ 5635 public void installPackage( 5636 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 5637 final String installerPackageName) { 5638 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null, 5639 null, null); 5640 } 5641 5642 @Override 5643 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 5644 int flags, String installerPackageName, Uri verificationURI, 5645 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 5646 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 5647 manifestDigest); 5648 installPackageWithVerificationAndEncryption(packageURI, observer, flags, 5649 installerPackageName, verificationParams, encryptionParams); 5650 } 5651 5652 public void installPackageWithVerificationAndEncryption(Uri packageURI, 5653 IPackageInstallObserver observer, int flags, String installerPackageName, 5654 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 5655 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 5656 null); 5657 5658 final int uid = Binder.getCallingUid(); 5659 UserHandle user; 5660 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 5661 user = UserHandle.ALL; 5662 } else { 5663 user = new UserHandle(UserHandle.getUserId(uid)); 5664 } 5665 5666 final int filteredFlags; 5667 5668 if (uid == Process.SHELL_UID || uid == 0) { 5669 if (DEBUG_INSTALL) { 5670 Slog.v(TAG, "Install from ADB"); 5671 } 5672 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 5673 } else { 5674 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 5675 } 5676 5677 verificationParams.setInstallerUid(uid); 5678 5679 final Message msg = mHandler.obtainMessage(INIT_COPY); 5680 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName, 5681 verificationParams, encryptionParams, user); 5682 mHandler.sendMessage(msg); 5683 } 5684 5685 /** 5686 * @hide 5687 */ 5688 @Override 5689 public int installExistingPackage(String packageName) { 5690 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 5691 null); 5692 PackageSetting pkgSetting; 5693 final int uid = Binder.getCallingUid(); 5694 final int userId = UserHandle.getUserId(uid); 5695 5696 long callingId = Binder.clearCallingIdentity(); 5697 try { 5698 boolean sendAdded = false; 5699 Bundle extras = new Bundle(1); 5700 5701 // writer 5702 synchronized (mPackages) { 5703 pkgSetting = mSettings.mPackages.get(packageName); 5704 if (pkgSetting == null) { 5705 return PackageManager.INSTALL_FAILED_INVALID_URI; 5706 } 5707 if (!pkgSetting.getInstalled(userId)) { 5708 pkgSetting.setInstalled(true, userId); 5709 mSettings.writePackageRestrictionsLPr(userId); 5710 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 5711 sendAdded = true; 5712 } 5713 } 5714 5715 if (sendAdded) { 5716 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 5717 packageName, extras, null, null, new int[] {userId}); 5718 } 5719 } finally { 5720 Binder.restoreCallingIdentity(callingId); 5721 } 5722 5723 return PackageManager.INSTALL_SUCCEEDED; 5724 } 5725 5726 @Override 5727 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 5728 mContext.enforceCallingOrSelfPermission( 5729 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 5730 "Only package verification agents can verify applications"); 5731 5732 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 5733 final PackageVerificationResponse response = new PackageVerificationResponse( 5734 verificationCode, Binder.getCallingUid()); 5735 msg.arg1 = id; 5736 msg.obj = response; 5737 mHandler.sendMessage(msg); 5738 } 5739 5740 @Override 5741 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 5742 long millisecondsToDelay) { 5743 mContext.enforceCallingOrSelfPermission( 5744 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 5745 "Only package verification agents can extend verification timeouts"); 5746 5747 final PackageVerificationState state = mPendingVerification.get(id); 5748 final PackageVerificationResponse response = new PackageVerificationResponse( 5749 verificationCodeAtTimeout, Binder.getCallingUid()); 5750 5751 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 5752 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 5753 } 5754 if (millisecondsToDelay < 0) { 5755 millisecondsToDelay = 0; 5756 } 5757 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 5758 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 5759 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 5760 } 5761 5762 if ((state != null) && !state.timeoutExtended()) { 5763 state.extendTimeout(); 5764 5765 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 5766 msg.arg1 = id; 5767 msg.obj = response; 5768 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 5769 } 5770 } 5771 5772 private void broadcastPackageVerified(int verificationId, Uri packageUri, 5773 int verificationCode) { 5774 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 5775 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 5776 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 5777 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 5778 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 5779 5780 mContext.sendBroadcast(intent, android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 5781 } 5782 5783 private ComponentName matchComponentForVerifier(String packageName, 5784 List<ResolveInfo> receivers) { 5785 ActivityInfo targetReceiver = null; 5786 5787 final int NR = receivers.size(); 5788 for (int i = 0; i < NR; i++) { 5789 final ResolveInfo info = receivers.get(i); 5790 if (info.activityInfo == null) { 5791 continue; 5792 } 5793 5794 if (packageName.equals(info.activityInfo.packageName)) { 5795 targetReceiver = info.activityInfo; 5796 break; 5797 } 5798 } 5799 5800 if (targetReceiver == null) { 5801 return null; 5802 } 5803 5804 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 5805 } 5806 5807 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 5808 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 5809 if (pkgInfo.verifiers.length == 0) { 5810 return null; 5811 } 5812 5813 final int N = pkgInfo.verifiers.length; 5814 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 5815 for (int i = 0; i < N; i++) { 5816 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 5817 5818 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 5819 receivers); 5820 if (comp == null) { 5821 continue; 5822 } 5823 5824 final int verifierUid = getUidForVerifier(verifierInfo); 5825 if (verifierUid == -1) { 5826 continue; 5827 } 5828 5829 if (DEBUG_VERIFY) { 5830 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 5831 + " with the correct signature"); 5832 } 5833 sufficientVerifiers.add(comp); 5834 verificationState.addSufficientVerifier(verifierUid); 5835 } 5836 5837 return sufficientVerifiers; 5838 } 5839 5840 private int getUidForVerifier(VerifierInfo verifierInfo) { 5841 synchronized (mPackages) { 5842 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 5843 if (pkg == null) { 5844 return -1; 5845 } else if (pkg.mSignatures.length != 1) { 5846 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 5847 + " has more than one signature; ignoring"); 5848 return -1; 5849 } 5850 5851 /* 5852 * If the public key of the package's signature does not match 5853 * our expected public key, then this is a different package and 5854 * we should skip. 5855 */ 5856 5857 final byte[] expectedPublicKey; 5858 try { 5859 final Signature verifierSig = pkg.mSignatures[0]; 5860 final PublicKey publicKey = verifierSig.getPublicKey(); 5861 expectedPublicKey = publicKey.getEncoded(); 5862 } catch (CertificateException e) { 5863 return -1; 5864 } 5865 5866 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 5867 5868 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 5869 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 5870 + " does not have the expected public key; ignoring"); 5871 return -1; 5872 } 5873 5874 return pkg.applicationInfo.uid; 5875 } 5876 } 5877 5878 public void finishPackageInstall(int token) { 5879 enforceSystemOrRoot("Only the system is allowed to finish installs"); 5880 5881 if (DEBUG_INSTALL) { 5882 Slog.v(TAG, "BM finishing package install for " + token); 5883 } 5884 5885 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 5886 mHandler.sendMessage(msg); 5887 } 5888 5889 /** 5890 * Get the verification agent timeout. 5891 * 5892 * @return verification timeout in milliseconds 5893 */ 5894 private long getVerificationTimeout() { 5895 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 5896 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 5897 DEFAULT_VERIFICATION_TIMEOUT); 5898 } 5899 5900 /** 5901 * Get the default verification agent response code. 5902 * 5903 * @return default verification response code 5904 */ 5905 private int getDefaultVerificationResponse() { 5906 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 5907 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 5908 DEFAULT_VERIFICATION_RESPONSE); 5909 } 5910 5911 /** 5912 * Check whether or not package verification has been enabled. 5913 * 5914 * @return true if verification should be performed 5915 */ 5916 private boolean isVerificationEnabled(int flags) { 5917 if (!DEFAULT_VERIFY_ENABLE) { 5918 return false; 5919 } 5920 5921 // Check if installing from ADB 5922 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 5923 // Check if the developer does not want package verification for ADB installs 5924 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 5925 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 5926 return false; 5927 } 5928 } 5929 5930 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 5931 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 5932 } 5933 5934 /** 5935 * Get the "allow unknown sources" setting. 5936 * 5937 * @return the current "allow unknown sources" setting 5938 */ 5939 private int getUnknownSourcesSettings() { 5940 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 5941 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 5942 -1); 5943 } 5944 5945 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 5946 final int uid = Binder.getCallingUid(); 5947 // writer 5948 synchronized (mPackages) { 5949 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 5950 if (targetPackageSetting == null) { 5951 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 5952 } 5953 5954 PackageSetting installerPackageSetting; 5955 if (installerPackageName != null) { 5956 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 5957 if (installerPackageSetting == null) { 5958 throw new IllegalArgumentException("Unknown installer package: " 5959 + installerPackageName); 5960 } 5961 } else { 5962 installerPackageSetting = null; 5963 } 5964 5965 Signature[] callerSignature; 5966 Object obj = mSettings.getUserIdLPr(uid); 5967 if (obj != null) { 5968 if (obj instanceof SharedUserSetting) { 5969 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 5970 } else if (obj instanceof PackageSetting) { 5971 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 5972 } else { 5973 throw new SecurityException("Bad object " + obj + " for uid " + uid); 5974 } 5975 } else { 5976 throw new SecurityException("Unknown calling uid " + uid); 5977 } 5978 5979 // Verify: can't set installerPackageName to a package that is 5980 // not signed with the same cert as the caller. 5981 if (installerPackageSetting != null) { 5982 if (compareSignatures(callerSignature, 5983 installerPackageSetting.signatures.mSignatures) 5984 != PackageManager.SIGNATURE_MATCH) { 5985 throw new SecurityException( 5986 "Caller does not have same cert as new installer package " 5987 + installerPackageName); 5988 } 5989 } 5990 5991 // Verify: if target already has an installer package, it must 5992 // be signed with the same cert as the caller. 5993 if (targetPackageSetting.installerPackageName != null) { 5994 PackageSetting setting = mSettings.mPackages.get( 5995 targetPackageSetting.installerPackageName); 5996 // If the currently set package isn't valid, then it's always 5997 // okay to change it. 5998 if (setting != null) { 5999 if (compareSignatures(callerSignature, 6000 setting.signatures.mSignatures) 6001 != PackageManager.SIGNATURE_MATCH) { 6002 throw new SecurityException( 6003 "Caller does not have same cert as old installer package " 6004 + targetPackageSetting.installerPackageName); 6005 } 6006 } 6007 } 6008 6009 // Okay! 6010 targetPackageSetting.installerPackageName = installerPackageName; 6011 scheduleWriteSettingsLocked(); 6012 } 6013 } 6014 6015 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 6016 // Queue up an async operation since the package installation may take a little while. 6017 mHandler.post(new Runnable() { 6018 public void run() { 6019 mHandler.removeCallbacks(this); 6020 // Result object to be returned 6021 PackageInstalledInfo res = new PackageInstalledInfo(); 6022 res.returnCode = currentStatus; 6023 res.uid = -1; 6024 res.pkg = null; 6025 res.removedInfo = new PackageRemovedInfo(); 6026 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 6027 args.doPreInstall(res.returnCode); 6028 synchronized (mInstallLock) { 6029 installPackageLI(args, true, res); 6030 } 6031 args.doPostInstall(res.returnCode, res.uid); 6032 } 6033 6034 // A restore should be performed at this point if (a) the install 6035 // succeeded, (b) the operation is not an update, and (c) the new 6036 // package has a backupAgent defined. 6037 final boolean update = res.removedInfo.removedPackage != null; 6038 boolean doRestore = (!update 6039 && res.pkg != null 6040 && res.pkg.applicationInfo.backupAgentName != null); 6041 6042 // Set up the post-install work request bookkeeping. This will be used 6043 // and cleaned up by the post-install event handling regardless of whether 6044 // there's a restore pass performed. Token values are >= 1. 6045 int token; 6046 if (mNextInstallToken < 0) mNextInstallToken = 1; 6047 token = mNextInstallToken++; 6048 6049 PostInstallData data = new PostInstallData(args, res); 6050 mRunningInstalls.put(token, data); 6051 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 6052 6053 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 6054 // Pass responsibility to the Backup Manager. It will perform a 6055 // restore if appropriate, then pass responsibility back to the 6056 // Package Manager to run the post-install observer callbacks 6057 // and broadcasts. 6058 IBackupManager bm = IBackupManager.Stub.asInterface( 6059 ServiceManager.getService(Context.BACKUP_SERVICE)); 6060 if (bm != null) { 6061 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 6062 + " to BM for possible restore"); 6063 try { 6064 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 6065 } catch (RemoteException e) { 6066 // can't happen; the backup manager is local 6067 } catch (Exception e) { 6068 Slog.e(TAG, "Exception trying to enqueue restore", e); 6069 doRestore = false; 6070 } 6071 } else { 6072 Slog.e(TAG, "Backup Manager not found!"); 6073 doRestore = false; 6074 } 6075 } 6076 6077 if (!doRestore) { 6078 // No restore possible, or the Backup Manager was mysteriously not 6079 // available -- just fire the post-install work request directly. 6080 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 6081 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 6082 mHandler.sendMessage(msg); 6083 } 6084 } 6085 }); 6086 } 6087 6088 private abstract class HandlerParams { 6089 private static final int MAX_RETRIES = 4; 6090 6091 /** 6092 * Number of times startCopy() has been attempted and had a non-fatal 6093 * error. 6094 */ 6095 private int mRetries = 0; 6096 6097 /** User handle for the user requesting the information or installation. */ 6098 private final UserHandle mUser; 6099 6100 HandlerParams(UserHandle user) { 6101 mUser = user; 6102 } 6103 6104 UserHandle getUser() { 6105 return mUser; 6106 } 6107 6108 final boolean startCopy() { 6109 boolean res; 6110 try { 6111 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy"); 6112 6113 if (++mRetries > MAX_RETRIES) { 6114 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 6115 mHandler.sendEmptyMessage(MCS_GIVE_UP); 6116 handleServiceError(); 6117 return false; 6118 } else { 6119 handleStartCopy(); 6120 res = true; 6121 } 6122 } catch (RemoteException e) { 6123 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 6124 mHandler.sendEmptyMessage(MCS_RECONNECT); 6125 res = false; 6126 } 6127 handleReturnCode(); 6128 return res; 6129 } 6130 6131 final void serviceError() { 6132 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 6133 handleServiceError(); 6134 handleReturnCode(); 6135 } 6136 6137 abstract void handleStartCopy() throws RemoteException; 6138 abstract void handleServiceError(); 6139 abstract void handleReturnCode(); 6140 } 6141 6142 class MeasureParams extends HandlerParams { 6143 private final PackageStats mStats; 6144 private boolean mSuccess; 6145 6146 private final IPackageStatsObserver mObserver; 6147 6148 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 6149 super(new UserHandle(stats.userHandle)); 6150 mObserver = observer; 6151 mStats = stats; 6152 } 6153 6154 @Override 6155 void handleStartCopy() throws RemoteException { 6156 synchronized (mInstallLock) { 6157 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 6158 } 6159 6160 final boolean mounted; 6161 if (Environment.isExternalStorageEmulated()) { 6162 mounted = true; 6163 } else { 6164 final String status = Environment.getExternalStorageState(); 6165 mounted = (Environment.MEDIA_MOUNTED.equals(status) 6166 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 6167 } 6168 6169 if (mounted) { 6170 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 6171 6172 final File externalCacheDir = userEnv 6173 .getExternalStorageAppCacheDirectory(mStats.packageName); 6174 final long externalCacheSize = mContainerService 6175 .calculateDirectorySize(externalCacheDir.getPath()); 6176 mStats.externalCacheSize = externalCacheSize; 6177 6178 final File externalDataDir = userEnv 6179 .getExternalStorageAppDataDirectory(mStats.packageName); 6180 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir 6181 .getPath()); 6182 6183 if (externalCacheDir.getParentFile().equals(externalDataDir)) { 6184 externalDataSize -= externalCacheSize; 6185 } 6186 mStats.externalDataSize = externalDataSize; 6187 6188 final File externalMediaDir = userEnv 6189 .getExternalStorageAppMediaDirectory(mStats.packageName); 6190 mStats.externalMediaSize = mContainerService 6191 .calculateDirectorySize(externalMediaDir.getPath()); 6192 6193 final File externalObbDir = userEnv 6194 .getExternalStorageAppObbDirectory(mStats.packageName); 6195 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir 6196 .getPath()); 6197 } 6198 } 6199 6200 @Override 6201 void handleReturnCode() { 6202 if (mObserver != null) { 6203 try { 6204 mObserver.onGetStatsCompleted(mStats, mSuccess); 6205 } catch (RemoteException e) { 6206 Slog.i(TAG, "Observer no longer exists."); 6207 } 6208 } 6209 } 6210 6211 @Override 6212 void handleServiceError() { 6213 Slog.e(TAG, "Could not measure application " + mStats.packageName 6214 + " external storage"); 6215 } 6216 } 6217 6218 class InstallParams extends HandlerParams { 6219 final IPackageInstallObserver observer; 6220 int flags; 6221 6222 private final Uri mPackageURI; 6223 final String installerPackageName; 6224 final VerificationParams verificationParams; 6225 private InstallArgs mArgs; 6226 private int mRet; 6227 private File mTempPackage; 6228 final ContainerEncryptionParams encryptionParams; 6229 6230 InstallParams(Uri packageURI, 6231 IPackageInstallObserver observer, int flags, 6232 String installerPackageName, VerificationParams verificationParams, 6233 ContainerEncryptionParams encryptionParams, UserHandle user) { 6234 super(user); 6235 this.mPackageURI = packageURI; 6236 this.flags = flags; 6237 this.observer = observer; 6238 this.installerPackageName = installerPackageName; 6239 this.verificationParams = verificationParams; 6240 this.encryptionParams = encryptionParams; 6241 } 6242 6243 public ManifestDigest getManifestDigest() { 6244 if (verificationParams == null) { 6245 return null; 6246 } 6247 return verificationParams.getManifestDigest(); 6248 } 6249 6250 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 6251 String packageName = pkgLite.packageName; 6252 int installLocation = pkgLite.installLocation; 6253 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 6254 // reader 6255 synchronized (mPackages) { 6256 PackageParser.Package pkg = mPackages.get(packageName); 6257 if (pkg != null) { 6258 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 6259 // Check for downgrading. 6260 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 6261 if (pkgLite.versionCode < pkg.mVersionCode) { 6262 Slog.w(TAG, "Can't install update of " + packageName 6263 + " update version " + pkgLite.versionCode 6264 + " is older than installed version " 6265 + pkg.mVersionCode); 6266 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 6267 } 6268 } 6269 // Check for updated system application. 6270 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 6271 if (onSd) { 6272 Slog.w(TAG, "Cannot install update to system app on sdcard"); 6273 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 6274 } 6275 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6276 } else { 6277 if (onSd) { 6278 // Install flag overrides everything. 6279 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6280 } 6281 // If current upgrade specifies particular preference 6282 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 6283 // Application explicitly specified internal. 6284 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6285 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 6286 // App explictly prefers external. Let policy decide 6287 } else { 6288 // Prefer previous location 6289 if (isExternal(pkg)) { 6290 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6291 } 6292 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6293 } 6294 } 6295 } else { 6296 // Invalid install. Return error code 6297 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 6298 } 6299 } 6300 } 6301 // All the special cases have been taken care of. 6302 // Return result based on recommended install location. 6303 if (onSd) { 6304 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6305 } 6306 return pkgLite.recommendedInstallLocation; 6307 } 6308 6309 /* 6310 * Invoke remote method to get package information and install 6311 * location values. Override install location based on default 6312 * policy if needed and then create install arguments based 6313 * on the install location. 6314 */ 6315 public void handleStartCopy() throws RemoteException { 6316 int ret = PackageManager.INSTALL_SUCCEEDED; 6317 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 6318 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 6319 PackageInfoLite pkgLite = null; 6320 6321 if (onInt && onSd) { 6322 // Check if both bits are set. 6323 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 6324 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 6325 } else { 6326 final long lowThreshold; 6327 6328 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 6329 .getService(DeviceStorageMonitorService.SERVICE); 6330 if (dsm == null) { 6331 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 6332 lowThreshold = 0L; 6333 } else { 6334 lowThreshold = dsm.getMemoryLowThreshold(); 6335 } 6336 6337 try { 6338 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 6339 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6340 6341 final File packageFile; 6342 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 6343 ParcelFileDescriptor out = null; 6344 6345 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 6346 if (mTempPackage != null) { 6347 try { 6348 out = ParcelFileDescriptor.open(mTempPackage, 6349 ParcelFileDescriptor.MODE_READ_WRITE); 6350 } catch (FileNotFoundException e) { 6351 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 6352 } 6353 6354 // Make a temporary file for decryption. 6355 ret = mContainerService 6356 .copyResource(mPackageURI, encryptionParams, out); 6357 6358 packageFile = mTempPackage; 6359 6360 FileUtils.setPermissions(packageFile.getAbsolutePath(), 6361 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 6362 | FileUtils.S_IROTH, 6363 -1, -1); 6364 } else { 6365 packageFile = null; 6366 } 6367 } else { 6368 packageFile = new File(mPackageURI.getPath()); 6369 } 6370 6371 if (packageFile != null) { 6372 // Remote call to find out default install location 6373 pkgLite = mContainerService.getMinimalPackageInfo( 6374 packageFile.getAbsolutePath(), flags, lowThreshold); 6375 } 6376 } finally { 6377 mContext.revokeUriPermission(mPackageURI, 6378 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6379 } 6380 } 6381 6382 if (ret == PackageManager.INSTALL_SUCCEEDED) { 6383 int loc = pkgLite.recommendedInstallLocation; 6384 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 6385 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 6386 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 6387 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 6388 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 6389 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6390 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 6391 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 6392 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 6393 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 6394 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 6395 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 6396 } else if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 6397 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 6398 } else { 6399 // Override with defaults if needed. 6400 loc = installLocationPolicy(pkgLite, flags); 6401 if (!onSd && !onInt) { 6402 // Override install location with flags 6403 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 6404 // Set the flag to install on external media. 6405 flags |= PackageManager.INSTALL_EXTERNAL; 6406 flags &= ~PackageManager.INSTALL_INTERNAL; 6407 } else { 6408 // Make sure the flag for installing on external 6409 // media is unset 6410 flags |= PackageManager.INSTALL_INTERNAL; 6411 flags &= ~PackageManager.INSTALL_EXTERNAL; 6412 } 6413 } 6414 } 6415 } 6416 6417 final InstallArgs args = createInstallArgs(this); 6418 mArgs = args; 6419 6420 if (ret == PackageManager.INSTALL_SUCCEEDED) { 6421 /* 6422 * Determine if we have any installed package verifiers. If we 6423 * do, then we'll defer to them to verify the packages. 6424 */ 6425 final int requiredUid = mRequiredVerifierPackage == null ? -1 6426 : getPackageUid(mRequiredVerifierPackage, 0); 6427 if (requiredUid != -1 && isVerificationEnabled(flags)) { 6428 final Intent verification = new Intent( 6429 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 6430 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 6431 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6432 6433 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 6434 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 6435 0 /* TODO: Which userId? */); 6436 6437 if (DEBUG_VERIFY) { 6438 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 6439 + verification.toString() + " with " + pkgLite.verifiers.length 6440 + " optional verifiers"); 6441 } 6442 6443 final int verificationId = mPendingVerificationToken++; 6444 6445 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 6446 6447 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 6448 installerPackageName); 6449 6450 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 6451 6452 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 6453 pkgLite.packageName); 6454 6455 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 6456 pkgLite.versionCode); 6457 6458 if (verificationParams != null) { 6459 if (verificationParams.getVerificationURI() != null) { 6460 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 6461 verificationParams.getVerificationURI()); 6462 } 6463 if (verificationParams.getOriginatingURI() != null) { 6464 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 6465 verificationParams.getOriginatingURI()); 6466 } 6467 if (verificationParams.getReferrer() != null) { 6468 verification.putExtra(Intent.EXTRA_REFERRER, 6469 verificationParams.getReferrer()); 6470 } 6471 if (verificationParams.getInstallerUid() >= 0) { 6472 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 6473 verificationParams.getInstallerUid()); 6474 } 6475 } 6476 6477 final PackageVerificationState verificationState = new PackageVerificationState( 6478 requiredUid, args); 6479 6480 mPendingVerification.append(verificationId, verificationState); 6481 6482 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 6483 receivers, verificationState); 6484 6485 /* 6486 * If any sufficient verifiers were listed in the package 6487 * manifest, attempt to ask them. 6488 */ 6489 if (sufficientVerifiers != null) { 6490 final int N = sufficientVerifiers.size(); 6491 if (N == 0) { 6492 Slog.i(TAG, "Additional verifiers required, but none installed."); 6493 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 6494 } else { 6495 for (int i = 0; i < N; i++) { 6496 final ComponentName verifierComponent = sufficientVerifiers.get(i); 6497 6498 final Intent sufficientIntent = new Intent(verification); 6499 sufficientIntent.setComponent(verifierComponent); 6500 6501 mContext.sendBroadcast(sufficientIntent); 6502 } 6503 } 6504 } 6505 6506 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 6507 mRequiredVerifierPackage, receivers); 6508 if (ret == PackageManager.INSTALL_SUCCEEDED 6509 && mRequiredVerifierPackage != null) { 6510 /* 6511 * Send the intent to the required verification agent, 6512 * but only start the verification timeout after the 6513 * target BroadcastReceivers have run. 6514 */ 6515 verification.setComponent(requiredVerifierComponent); 6516 mContext.sendOrderedBroadcast(verification, 6517 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 6518 new BroadcastReceiver() { 6519 @Override 6520 public void onReceive(Context context, Intent intent) { 6521 final Message msg = mHandler 6522 .obtainMessage(CHECK_PENDING_VERIFICATION); 6523 msg.arg1 = verificationId; 6524 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 6525 } 6526 }, null, 0, null, null); 6527 6528 /* 6529 * We don't want the copy to proceed until verification 6530 * succeeds, so null out this field. 6531 */ 6532 mArgs = null; 6533 } 6534 } else { 6535 /* 6536 * No package verification is enabled, so immediately start 6537 * the remote call to initiate copy using temporary file. 6538 */ 6539 ret = args.copyApk(mContainerService, true); 6540 } 6541 } 6542 6543 mRet = ret; 6544 } 6545 6546 @Override 6547 void handleReturnCode() { 6548 // If mArgs is null, then MCS couldn't be reached. When it 6549 // reconnects, it will try again to install. At that point, this 6550 // will succeed. 6551 if (mArgs != null) { 6552 processPendingInstall(mArgs, mRet); 6553 6554 if (mTempPackage != null) { 6555 if (!mTempPackage.delete()) { 6556 Slog.w(TAG, "Couldn't delete temporary file: " + 6557 mTempPackage.getAbsolutePath()); 6558 } 6559 } 6560 } 6561 } 6562 6563 @Override 6564 void handleServiceError() { 6565 mArgs = createInstallArgs(this); 6566 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6567 } 6568 6569 public boolean isForwardLocked() { 6570 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6571 } 6572 6573 public Uri getPackageUri() { 6574 if (mTempPackage != null) { 6575 return Uri.fromFile(mTempPackage); 6576 } else { 6577 return mPackageURI; 6578 } 6579 } 6580 } 6581 6582 /* 6583 * Utility class used in movePackage api. 6584 * srcArgs and targetArgs are not set for invalid flags and make 6585 * sure to do null checks when invoking methods on them. 6586 * We probably want to return ErrorPrams for both failed installs 6587 * and moves. 6588 */ 6589 class MoveParams extends HandlerParams { 6590 final IPackageMoveObserver observer; 6591 final int flags; 6592 final String packageName; 6593 final InstallArgs srcArgs; 6594 final InstallArgs targetArgs; 6595 int uid; 6596 int mRet; 6597 6598 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 6599 String packageName, String dataDir, int uid, UserHandle user) { 6600 super(user); 6601 this.srcArgs = srcArgs; 6602 this.observer = observer; 6603 this.flags = flags; 6604 this.packageName = packageName; 6605 this.uid = uid; 6606 if (srcArgs != null) { 6607 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 6608 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir); 6609 } else { 6610 targetArgs = null; 6611 } 6612 } 6613 6614 public void handleStartCopy() throws RemoteException { 6615 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6616 // Check for storage space on target medium 6617 if (!targetArgs.checkFreeStorage(mContainerService)) { 6618 Log.w(TAG, "Insufficient storage to install"); 6619 return; 6620 } 6621 6622 mRet = srcArgs.doPreCopy(); 6623 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6624 return; 6625 } 6626 6627 mRet = targetArgs.copyApk(mContainerService, false); 6628 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6629 srcArgs.doPostCopy(uid); 6630 return; 6631 } 6632 6633 mRet = srcArgs.doPostCopy(uid); 6634 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6635 return; 6636 } 6637 6638 mRet = targetArgs.doPreInstall(mRet); 6639 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6640 return; 6641 } 6642 6643 if (DEBUG_SD_INSTALL) { 6644 StringBuilder builder = new StringBuilder(); 6645 if (srcArgs != null) { 6646 builder.append("src: "); 6647 builder.append(srcArgs.getCodePath()); 6648 } 6649 if (targetArgs != null) { 6650 builder.append(" target : "); 6651 builder.append(targetArgs.getCodePath()); 6652 } 6653 Log.i(TAG, builder.toString()); 6654 } 6655 } 6656 6657 @Override 6658 void handleReturnCode() { 6659 targetArgs.doPostInstall(mRet, uid); 6660 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 6661 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 6662 currentStatus = PackageManager.MOVE_SUCCEEDED; 6663 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 6664 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 6665 } 6666 processPendingMove(this, currentStatus); 6667 } 6668 6669 @Override 6670 void handleServiceError() { 6671 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6672 } 6673 } 6674 6675 /** 6676 * Used during creation of InstallArgs 6677 * 6678 * @param flags package installation flags 6679 * @return true if should be installed on external storage 6680 */ 6681 private static boolean installOnSd(int flags) { 6682 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 6683 return false; 6684 } 6685 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 6686 return true; 6687 } 6688 return false; 6689 } 6690 6691 /** 6692 * Used during creation of InstallArgs 6693 * 6694 * @param flags package installation flags 6695 * @return true if should be installed as forward locked 6696 */ 6697 private static boolean installForwardLocked(int flags) { 6698 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6699 } 6700 6701 private InstallArgs createInstallArgs(InstallParams params) { 6702 if (installOnSd(params.flags) || params.isForwardLocked()) { 6703 return new AsecInstallArgs(params); 6704 } else { 6705 return new FileInstallArgs(params); 6706 } 6707 } 6708 6709 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 6710 String nativeLibraryPath) { 6711 final boolean isInAsec; 6712 if (installOnSd(flags)) { 6713 /* Apps on SD card are always in ASEC containers. */ 6714 isInAsec = true; 6715 } else if (installForwardLocked(flags) 6716 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 6717 /* 6718 * Forward-locked apps are only in ASEC containers if they're the 6719 * new style 6720 */ 6721 isInAsec = true; 6722 } else { 6723 isInAsec = false; 6724 } 6725 6726 if (isInAsec) { 6727 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 6728 installOnSd(flags), installForwardLocked(flags)); 6729 } else { 6730 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath); 6731 } 6732 } 6733 6734 // Used by package mover 6735 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) { 6736 if (installOnSd(flags) || installForwardLocked(flags)) { 6737 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 6738 + AsecInstallArgs.RES_FILE_NAME); 6739 return new AsecInstallArgs(packageURI, cid, installOnSd(flags), 6740 installForwardLocked(flags)); 6741 } else { 6742 return new FileInstallArgs(packageURI, pkgName, dataDir); 6743 } 6744 } 6745 6746 static abstract class InstallArgs { 6747 final IPackageInstallObserver observer; 6748 // Always refers to PackageManager flags only 6749 final int flags; 6750 final Uri packageURI; 6751 final String installerPackageName; 6752 final ManifestDigest manifestDigest; 6753 final UserHandle user; 6754 6755 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags, 6756 String installerPackageName, ManifestDigest manifestDigest, 6757 UserHandle user) { 6758 this.packageURI = packageURI; 6759 this.flags = flags; 6760 this.observer = observer; 6761 this.installerPackageName = installerPackageName; 6762 this.manifestDigest = manifestDigest; 6763 this.user = user; 6764 } 6765 6766 abstract void createCopyFile(); 6767 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 6768 abstract int doPreInstall(int status); 6769 abstract boolean doRename(int status, String pkgName, String oldCodePath); 6770 6771 abstract int doPostInstall(int status, int uid); 6772 abstract String getCodePath(); 6773 abstract String getResourcePath(); 6774 abstract String getNativeLibraryPath(); 6775 // Need installer lock especially for dex file removal. 6776 abstract void cleanUpResourcesLI(); 6777 abstract boolean doPostDeleteLI(boolean delete); 6778 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 6779 6780 /** 6781 * Called before the source arguments are copied. This is used mostly 6782 * for MoveParams when it needs to read the source file to put it in the 6783 * destination. 6784 */ 6785 int doPreCopy() { 6786 return PackageManager.INSTALL_SUCCEEDED; 6787 } 6788 6789 /** 6790 * Called after the source arguments are copied. This is used mostly for 6791 * MoveParams when it needs to read the source file to put it in the 6792 * destination. 6793 * 6794 * @return 6795 */ 6796 int doPostCopy(int uid) { 6797 return PackageManager.INSTALL_SUCCEEDED; 6798 } 6799 6800 protected boolean isFwdLocked() { 6801 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6802 } 6803 } 6804 6805 class FileInstallArgs extends InstallArgs { 6806 File installDir; 6807 String codeFileName; 6808 String resourceFileName; 6809 String libraryPath; 6810 boolean created = false; 6811 6812 FileInstallArgs(InstallParams params) { 6813 super(params.getPackageUri(), params.observer, params.flags, 6814 params.installerPackageName, params.getManifestDigest(), 6815 params.getUser()); 6816 } 6817 6818 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) { 6819 super(null, null, 0, null, null, null); 6820 File codeFile = new File(fullCodePath); 6821 installDir = codeFile.getParentFile(); 6822 codeFileName = fullCodePath; 6823 resourceFileName = fullResourcePath; 6824 libraryPath = nativeLibraryPath; 6825 } 6826 6827 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) { 6828 super(packageURI, null, 0, null, null, null); 6829 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 6830 String apkName = getNextCodePath(null, pkgName, ".apk"); 6831 codeFileName = new File(installDir, apkName + ".apk").getPath(); 6832 resourceFileName = getResourcePathFromCodePath(); 6833 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 6834 } 6835 6836 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 6837 final long lowThreshold; 6838 6839 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 6840 .getService(DeviceStorageMonitorService.SERVICE); 6841 if (dsm == null) { 6842 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 6843 lowThreshold = 0L; 6844 } else { 6845 if (dsm.isMemoryLow()) { 6846 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 6847 return false; 6848 } 6849 6850 lowThreshold = dsm.getMemoryLowThreshold(); 6851 } 6852 6853 try { 6854 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6855 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6856 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 6857 } finally { 6858 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6859 } 6860 } 6861 6862 String getCodePath() { 6863 return codeFileName; 6864 } 6865 6866 void createCopyFile() { 6867 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 6868 codeFileName = createTempPackageFile(installDir).getPath(); 6869 resourceFileName = getResourcePathFromCodePath(); 6870 libraryPath = getLibraryPathFromCodePath(); 6871 created = true; 6872 } 6873 6874 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 6875 if (temp) { 6876 // Generate temp file name 6877 createCopyFile(); 6878 } 6879 // Get a ParcelFileDescriptor to write to the output file 6880 File codeFile = new File(codeFileName); 6881 if (!created) { 6882 try { 6883 codeFile.createNewFile(); 6884 // Set permissions 6885 if (!setPermissions()) { 6886 // Failed setting permissions. 6887 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6888 } 6889 } catch (IOException e) { 6890 Slog.w(TAG, "Failed to create file " + codeFile); 6891 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6892 } 6893 } 6894 ParcelFileDescriptor out = null; 6895 try { 6896 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 6897 } catch (FileNotFoundException e) { 6898 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 6899 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6900 } 6901 // Copy the resource now 6902 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6903 try { 6904 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6905 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6906 ret = imcs.copyResource(packageURI, null, out); 6907 } finally { 6908 IoUtils.closeQuietly(out); 6909 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6910 } 6911 6912 if (isFwdLocked()) { 6913 final File destResourceFile = new File(getResourcePath()); 6914 6915 // Copy the public files 6916 try { 6917 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 6918 } catch (IOException e) { 6919 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 6920 + " forward-locked app."); 6921 destResourceFile.delete(); 6922 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6923 } 6924 } 6925 6926 final File nativeLibraryFile = new File(getNativeLibraryPath()); 6927 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 6928 if (nativeLibraryFile.exists()) { 6929 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 6930 nativeLibraryFile.delete(); 6931 } 6932 try { 6933 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 6934 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6935 return copyRet; 6936 } 6937 } catch (IOException e) { 6938 Slog.e(TAG, "Copying native libraries failed", e); 6939 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6940 } 6941 6942 return ret; 6943 } 6944 6945 int doPreInstall(int status) { 6946 if (status != PackageManager.INSTALL_SUCCEEDED) { 6947 cleanUp(); 6948 } 6949 return status; 6950 } 6951 6952 boolean doRename(int status, final String pkgName, String oldCodePath) { 6953 if (status != PackageManager.INSTALL_SUCCEEDED) { 6954 cleanUp(); 6955 return false; 6956 } else { 6957 final File oldCodeFile = new File(getCodePath()); 6958 final File oldResourceFile = new File(getResourcePath()); 6959 final File oldLibraryFile = new File(getNativeLibraryPath()); 6960 6961 // Rename APK file based on packageName 6962 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 6963 final File newCodeFile = new File(installDir, apkName + ".apk"); 6964 if (!oldCodeFile.renameTo(newCodeFile)) { 6965 return false; 6966 } 6967 codeFileName = newCodeFile.getPath(); 6968 6969 // Rename public resource file if it's forward-locked. 6970 final File newResFile = new File(getResourcePathFromCodePath()); 6971 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 6972 return false; 6973 } 6974 resourceFileName = newResFile.getPath(); 6975 6976 // Rename library path 6977 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 6978 if (newLibraryFile.exists()) { 6979 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 6980 newLibraryFile.delete(); 6981 } 6982 if (!oldLibraryFile.renameTo(newLibraryFile)) { 6983 Slog.e(TAG, "Cannot rename native library directory " 6984 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 6985 return false; 6986 } 6987 libraryPath = newLibraryFile.getPath(); 6988 6989 // Attempt to set permissions 6990 if (!setPermissions()) { 6991 return false; 6992 } 6993 6994 if (!SELinux.restorecon(newCodeFile)) { 6995 return false; 6996 } 6997 6998 return true; 6999 } 7000 } 7001 7002 int doPostInstall(int status, int uid) { 7003 if (status != PackageManager.INSTALL_SUCCEEDED) { 7004 cleanUp(); 7005 } 7006 return status; 7007 } 7008 7009 String getResourcePath() { 7010 return resourceFileName; 7011 } 7012 7013 private String getResourcePathFromCodePath() { 7014 final String codePath = getCodePath(); 7015 if (isFwdLocked()) { 7016 final StringBuilder sb = new StringBuilder(); 7017 7018 sb.append(mAppInstallDir.getPath()); 7019 sb.append('/'); 7020 sb.append(getApkName(codePath)); 7021 sb.append(".zip"); 7022 7023 /* 7024 * If our APK is a temporary file, mark the resource as a 7025 * temporary file as well so it can be cleaned up after 7026 * catastrophic failure. 7027 */ 7028 if (codePath.endsWith(".tmp")) { 7029 sb.append(".tmp"); 7030 } 7031 7032 return sb.toString(); 7033 } else { 7034 return codePath; 7035 } 7036 } 7037 7038 private String getLibraryPathFromCodePath() { 7039 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 7040 } 7041 7042 @Override 7043 String getNativeLibraryPath() { 7044 if (libraryPath == null) { 7045 libraryPath = getLibraryPathFromCodePath(); 7046 } 7047 return libraryPath; 7048 } 7049 7050 private boolean cleanUp() { 7051 boolean ret = true; 7052 String sourceDir = getCodePath(); 7053 String publicSourceDir = getResourcePath(); 7054 if (sourceDir != null) { 7055 File sourceFile = new File(sourceDir); 7056 if (!sourceFile.exists()) { 7057 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 7058 ret = false; 7059 } 7060 // Delete application's code and resources 7061 sourceFile.delete(); 7062 } 7063 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 7064 final File publicSourceFile = new File(publicSourceDir); 7065 if (!publicSourceFile.exists()) { 7066 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 7067 } 7068 if (publicSourceFile.exists()) { 7069 publicSourceFile.delete(); 7070 } 7071 } 7072 7073 if (libraryPath != null) { 7074 File nativeLibraryFile = new File(libraryPath); 7075 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 7076 if (!nativeLibraryFile.delete()) { 7077 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 7078 } 7079 } 7080 7081 return ret; 7082 } 7083 7084 void cleanUpResourcesLI() { 7085 String sourceDir = getCodePath(); 7086 if (cleanUp()) { 7087 int retCode = mInstaller.rmdex(sourceDir); 7088 if (retCode < 0) { 7089 Slog.w(TAG, "Couldn't remove dex file for package: " 7090 + " at location " 7091 + sourceDir + ", retcode=" + retCode); 7092 // we don't consider this to be a failure of the core package deletion 7093 } 7094 } 7095 } 7096 7097 private boolean setPermissions() { 7098 // TODO Do this in a more elegant way later on. for now just a hack 7099 if (!isFwdLocked()) { 7100 final int filePermissions = 7101 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 7102 |FileUtils.S_IROTH; 7103 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 7104 if (retCode != 0) { 7105 Slog.e(TAG, "Couldn't set new package file permissions for " + 7106 getCodePath() 7107 + ". The return code was: " + retCode); 7108 // TODO Define new internal error 7109 return false; 7110 } 7111 return true; 7112 } 7113 return true; 7114 } 7115 7116 boolean doPostDeleteLI(boolean delete) { 7117 // XXX err, shouldn't we respect the delete flag? 7118 cleanUpResourcesLI(); 7119 return true; 7120 } 7121 } 7122 7123 private boolean isAsecExternal(String cid) { 7124 final String asecPath = PackageHelper.getSdFilesystem(cid); 7125 return !asecPath.startsWith(mAsecInternalPath); 7126 } 7127 7128 /** 7129 * Extract the MountService "container ID" from the full code path of an 7130 * .apk. 7131 */ 7132 static String cidFromCodePath(String fullCodePath) { 7133 int eidx = fullCodePath.lastIndexOf("/"); 7134 String subStr1 = fullCodePath.substring(0, eidx); 7135 int sidx = subStr1.lastIndexOf("/"); 7136 return subStr1.substring(sidx+1, eidx); 7137 } 7138 7139 class AsecInstallArgs extends InstallArgs { 7140 static final String RES_FILE_NAME = "pkg.apk"; 7141 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 7142 7143 String cid; 7144 String packagePath; 7145 String resourcePath; 7146 String libraryPath; 7147 7148 AsecInstallArgs(InstallParams params) { 7149 super(params.getPackageUri(), params.observer, params.flags, 7150 params.installerPackageName, params.getManifestDigest(), 7151 params.getUser()); 7152 } 7153 7154 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 7155 boolean isExternal, boolean isForwardLocked) { 7156 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 7157 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 7158 null, null, null); 7159 // Extract cid from fullCodePath 7160 int eidx = fullCodePath.lastIndexOf("/"); 7161 String subStr1 = fullCodePath.substring(0, eidx); 7162 int sidx = subStr1.lastIndexOf("/"); 7163 cid = subStr1.substring(sidx+1, eidx); 7164 setCachePath(subStr1); 7165 } 7166 7167 AsecInstallArgs(String cid, boolean isForwardLocked) { 7168 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 7169 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 7170 null, null, null); 7171 this.cid = cid; 7172 setCachePath(PackageHelper.getSdDir(cid)); 7173 } 7174 7175 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) { 7176 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 7177 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 7178 null, null, null); 7179 this.cid = cid; 7180 } 7181 7182 void createCopyFile() { 7183 cid = getTempContainerId(); 7184 } 7185 7186 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 7187 try { 7188 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 7189 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7190 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 7191 } finally { 7192 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 7193 } 7194 } 7195 7196 private final boolean isExternal() { 7197 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 7198 } 7199 7200 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 7201 if (temp) { 7202 createCopyFile(); 7203 } else { 7204 /* 7205 * Pre-emptively destroy the container since it's destroyed if 7206 * copying fails due to it existing anyway. 7207 */ 7208 PackageHelper.destroySdDir(cid); 7209 } 7210 7211 final String newCachePath; 7212 try { 7213 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 7214 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7215 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 7216 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 7217 } finally { 7218 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 7219 } 7220 7221 if (newCachePath != null) { 7222 setCachePath(newCachePath); 7223 return PackageManager.INSTALL_SUCCEEDED; 7224 } else { 7225 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7226 } 7227 } 7228 7229 @Override 7230 String getCodePath() { 7231 return packagePath; 7232 } 7233 7234 @Override 7235 String getResourcePath() { 7236 return resourcePath; 7237 } 7238 7239 @Override 7240 String getNativeLibraryPath() { 7241 return libraryPath; 7242 } 7243 7244 int doPreInstall(int status) { 7245 if (status != PackageManager.INSTALL_SUCCEEDED) { 7246 // Destroy container 7247 PackageHelper.destroySdDir(cid); 7248 } else { 7249 boolean mounted = PackageHelper.isContainerMounted(cid); 7250 if (!mounted) { 7251 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 7252 Process.SYSTEM_UID); 7253 if (newCachePath != null) { 7254 setCachePath(newCachePath); 7255 } else { 7256 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7257 } 7258 } 7259 } 7260 return status; 7261 } 7262 7263 boolean doRename(int status, final String pkgName, 7264 String oldCodePath) { 7265 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 7266 String newCachePath = null; 7267 if (PackageHelper.isContainerMounted(cid)) { 7268 // Unmount the container 7269 if (!PackageHelper.unMountSdDir(cid)) { 7270 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 7271 return false; 7272 } 7273 } 7274 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 7275 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 7276 " which might be stale. Will try to clean up."); 7277 // Clean up the stale container and proceed to recreate. 7278 if (!PackageHelper.destroySdDir(newCacheId)) { 7279 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 7280 return false; 7281 } 7282 // Successfully cleaned up stale container. Try to rename again. 7283 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 7284 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 7285 + " inspite of cleaning it up."); 7286 return false; 7287 } 7288 } 7289 if (!PackageHelper.isContainerMounted(newCacheId)) { 7290 Slog.w(TAG, "Mounting container " + newCacheId); 7291 newCachePath = PackageHelper.mountSdDir(newCacheId, 7292 getEncryptKey(), Process.SYSTEM_UID); 7293 } else { 7294 newCachePath = PackageHelper.getSdDir(newCacheId); 7295 } 7296 if (newCachePath == null) { 7297 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 7298 return false; 7299 } 7300 Log.i(TAG, "Succesfully renamed " + cid + 7301 " to " + newCacheId + 7302 " at new path: " + newCachePath); 7303 cid = newCacheId; 7304 setCachePath(newCachePath); 7305 return true; 7306 } 7307 7308 private void setCachePath(String newCachePath) { 7309 File cachePath = new File(newCachePath); 7310 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 7311 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 7312 7313 if (isFwdLocked()) { 7314 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 7315 } else { 7316 resourcePath = packagePath; 7317 } 7318 } 7319 7320 int doPostInstall(int status, int uid) { 7321 if (status != PackageManager.INSTALL_SUCCEEDED) { 7322 cleanUp(); 7323 } else { 7324 final int groupOwner; 7325 final String protectedFile; 7326 if (isFwdLocked()) { 7327 groupOwner = UserHandle.getSharedAppGid(uid); 7328 protectedFile = RES_FILE_NAME; 7329 } else { 7330 groupOwner = -1; 7331 protectedFile = null; 7332 } 7333 7334 if (uid < Process.FIRST_APPLICATION_UID 7335 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 7336 Slog.e(TAG, "Failed to finalize " + cid); 7337 PackageHelper.destroySdDir(cid); 7338 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7339 } 7340 7341 boolean mounted = PackageHelper.isContainerMounted(cid); 7342 if (!mounted) { 7343 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 7344 } 7345 } 7346 return status; 7347 } 7348 7349 private void cleanUp() { 7350 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 7351 7352 // Destroy secure container 7353 PackageHelper.destroySdDir(cid); 7354 } 7355 7356 void cleanUpResourcesLI() { 7357 String sourceFile = getCodePath(); 7358 // Remove dex file 7359 int retCode = mInstaller.rmdex(sourceFile); 7360 if (retCode < 0) { 7361 Slog.w(TAG, "Couldn't remove dex file for package: " 7362 + " at location " 7363 + sourceFile.toString() + ", retcode=" + retCode); 7364 // we don't consider this to be a failure of the core package deletion 7365 } 7366 cleanUp(); 7367 } 7368 7369 boolean matchContainer(String app) { 7370 if (cid.startsWith(app)) { 7371 return true; 7372 } 7373 return false; 7374 } 7375 7376 String getPackageName() { 7377 return getAsecPackageName(cid); 7378 } 7379 7380 boolean doPostDeleteLI(boolean delete) { 7381 boolean ret = false; 7382 boolean mounted = PackageHelper.isContainerMounted(cid); 7383 if (mounted) { 7384 // Unmount first 7385 ret = PackageHelper.unMountSdDir(cid); 7386 } 7387 if (ret && delete) { 7388 cleanUpResourcesLI(); 7389 } 7390 return ret; 7391 } 7392 7393 @Override 7394 int doPreCopy() { 7395 if (isFwdLocked()) { 7396 if (!PackageHelper.fixSdPermissions(cid, 7397 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 7398 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7399 } 7400 } 7401 7402 return PackageManager.INSTALL_SUCCEEDED; 7403 } 7404 7405 @Override 7406 int doPostCopy(int uid) { 7407 if (isFwdLocked()) { 7408 if (uid < Process.FIRST_APPLICATION_UID 7409 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 7410 RES_FILE_NAME)) { 7411 Slog.e(TAG, "Failed to finalize " + cid); 7412 PackageHelper.destroySdDir(cid); 7413 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7414 } 7415 } 7416 7417 return PackageManager.INSTALL_SUCCEEDED; 7418 } 7419 }; 7420 7421 static String getAsecPackageName(String packageCid) { 7422 int idx = packageCid.lastIndexOf("-"); 7423 if (idx == -1) { 7424 return packageCid; 7425 } 7426 return packageCid.substring(0, idx); 7427 } 7428 7429 // Utility method used to create code paths based on package name and available index. 7430 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 7431 String idxStr = ""; 7432 int idx = 1; 7433 // Fall back to default value of idx=1 if prefix is not 7434 // part of oldCodePath 7435 if (oldCodePath != null) { 7436 String subStr = oldCodePath; 7437 // Drop the suffix right away 7438 if (subStr.endsWith(suffix)) { 7439 subStr = subStr.substring(0, subStr.length() - suffix.length()); 7440 } 7441 // If oldCodePath already contains prefix find out the 7442 // ending index to either increment or decrement. 7443 int sidx = subStr.lastIndexOf(prefix); 7444 if (sidx != -1) { 7445 subStr = subStr.substring(sidx + prefix.length()); 7446 if (subStr != null) { 7447 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 7448 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 7449 } 7450 try { 7451 idx = Integer.parseInt(subStr); 7452 if (idx <= 1) { 7453 idx++; 7454 } else { 7455 idx--; 7456 } 7457 } catch(NumberFormatException e) { 7458 } 7459 } 7460 } 7461 } 7462 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 7463 return prefix + idxStr; 7464 } 7465 7466 // Utility method used to ignore ADD/REMOVE events 7467 // by directory observer. 7468 private static boolean ignoreCodePath(String fullPathStr) { 7469 String apkName = getApkName(fullPathStr); 7470 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 7471 if (idx != -1 && ((idx+1) < apkName.length())) { 7472 // Make sure the package ends with a numeral 7473 String version = apkName.substring(idx+1); 7474 try { 7475 Integer.parseInt(version); 7476 return true; 7477 } catch (NumberFormatException e) {} 7478 } 7479 return false; 7480 } 7481 7482 // Utility method that returns the relative package path with respect 7483 // to the installation directory. Like say for /data/data/com.test-1.apk 7484 // string com.test-1 is returned. 7485 static String getApkName(String codePath) { 7486 if (codePath == null) { 7487 return null; 7488 } 7489 int sidx = codePath.lastIndexOf("/"); 7490 int eidx = codePath.lastIndexOf("."); 7491 if (eidx == -1) { 7492 eidx = codePath.length(); 7493 } else if (eidx == 0) { 7494 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 7495 return null; 7496 } 7497 return codePath.substring(sidx+1, eidx); 7498 } 7499 7500 class PackageInstalledInfo { 7501 String name; 7502 int uid; 7503 // The set of users that originally had this package installed. 7504 int[] origUsers; 7505 // The set of users that now have this package installed. 7506 int[] newUsers; 7507 PackageParser.Package pkg; 7508 int returnCode; 7509 PackageRemovedInfo removedInfo; 7510 } 7511 7512 /* 7513 * Install a non-existing package. 7514 */ 7515 private void installNewPackageLI(PackageParser.Package pkg, 7516 int parseFlags, int scanMode, UserHandle user, 7517 String installerPackageName, PackageInstalledInfo res) { 7518 // Remember this for later, in case we need to rollback this install 7519 String pkgName = pkg.packageName; 7520 7521 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 7522 synchronized(mPackages) { 7523 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 7524 // A package with the same name is already installed, though 7525 // it has been renamed to an older name. The package we 7526 // are trying to install should be installed as an update to 7527 // the existing one, but that has not been requested, so bail. 7528 Slog.w(TAG, "Attempt to re-install " + pkgName 7529 + " without first uninstalling package running as " 7530 + mSettings.mRenamedPackages.get(pkgName)); 7531 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7532 return; 7533 } 7534 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 7535 // Don't allow installation over an existing package with the same name. 7536 Slog.w(TAG, "Attempt to re-install " + pkgName 7537 + " without first uninstalling."); 7538 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7539 return; 7540 } 7541 } 7542 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7543 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 7544 System.currentTimeMillis(), user); 7545 if (newPackage == null) { 7546 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7547 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7548 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7549 } 7550 } else { 7551 updateSettingsLI(newPackage, 7552 installerPackageName, 7553 res); 7554 // delete the partially installed application. the data directory will have to be 7555 // restored if it was already existing 7556 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7557 // remove package from internal structures. Note that we want deletePackageX to 7558 // delete the package data and cache directories that it created in 7559 // scanPackageLocked, unless those directories existed before we even tried to 7560 // install. 7561 deletePackageLI(pkgName, UserHandle.ALL, false, 7562 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 7563 res.removedInfo, true); 7564 } 7565 } 7566 } 7567 7568 private void replacePackageLI(PackageParser.Package pkg, 7569 int parseFlags, int scanMode, UserHandle user, 7570 String installerPackageName, PackageInstalledInfo res) { 7571 7572 PackageParser.Package oldPackage; 7573 String pkgName = pkg.packageName; 7574 // First find the old package info and check signatures 7575 synchronized(mPackages) { 7576 oldPackage = mPackages.get(pkgName); 7577 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 7578 != PackageManager.SIGNATURE_MATCH) { 7579 Slog.w(TAG, "New package has a different signature: " + pkgName); 7580 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 7581 return; 7582 } 7583 } 7584 boolean sysPkg = (isSystemApp(oldPackage)); 7585 if (sysPkg) { 7586 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 7587 user, installerPackageName, res); 7588 } else { 7589 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 7590 user, installerPackageName, res); 7591 } 7592 } 7593 7594 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 7595 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 7596 String installerPackageName, PackageInstalledInfo res) { 7597 PackageParser.Package newPackage = null; 7598 String pkgName = deletedPackage.packageName; 7599 boolean deletedPkg = true; 7600 boolean updatedSettings = false; 7601 7602 long origUpdateTime; 7603 if (pkg.mExtras != null) { 7604 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 7605 } else { 7606 origUpdateTime = 0; 7607 } 7608 7609 // First delete the existing package while retaining the data directory 7610 if (!deletePackageLI(pkgName, null, true, PackageManager.DELETE_KEEP_DATA, 7611 res.removedInfo, true)) { 7612 // If the existing package wasn't successfully deleted 7613 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 7614 deletedPkg = false; 7615 } else { 7616 // Successfully deleted the old package. Now proceed with re-installation 7617 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7618 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 7619 System.currentTimeMillis(), user); 7620 if (newPackage == null) { 7621 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7622 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7623 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7624 } 7625 } else { 7626 updateSettingsLI(newPackage, 7627 installerPackageName, 7628 res); 7629 updatedSettings = true; 7630 } 7631 } 7632 7633 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7634 // remove package from internal structures. Note that we want deletePackageX to 7635 // delete the package data and cache directories that it created in 7636 // scanPackageLocked, unless those directories existed before we even tried to 7637 // install. 7638 if(updatedSettings) { 7639 deletePackageLI( 7640 pkgName, null, true, 7641 PackageManager.DELETE_KEEP_DATA, 7642 res.removedInfo, true); 7643 } 7644 // Since we failed to install the new package we need to restore the old 7645 // package that we deleted. 7646 if(deletedPkg) { 7647 File restoreFile = new File(deletedPackage.mPath); 7648 // Parse old package 7649 boolean oldOnSd = isExternal(deletedPackage); 7650 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 7651 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 7652 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 7653 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 7654 | SCAN_UPDATE_TIME; 7655 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 7656 origUpdateTime, null) == null) { 7657 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 7658 return; 7659 } 7660 // Restore of old package succeeded. Update permissions. 7661 // writer 7662 synchronized (mPackages) { 7663 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 7664 UPDATE_PERMISSIONS_ALL); 7665 // can downgrade to reader 7666 mSettings.writeLPr(); 7667 } 7668 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 7669 } 7670 } 7671 } 7672 7673 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 7674 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 7675 String installerPackageName, PackageInstalledInfo res) { 7676 PackageParser.Package newPackage = null; 7677 boolean updatedSettings = false; 7678 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 7679 PackageParser.PARSE_IS_SYSTEM; 7680 String packageName = deletedPackage.packageName; 7681 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 7682 if (packageName == null) { 7683 Slog.w(TAG, "Attempt to delete null packageName."); 7684 return; 7685 } 7686 PackageParser.Package oldPkg; 7687 PackageSetting oldPkgSetting; 7688 // reader 7689 synchronized (mPackages) { 7690 oldPkg = mPackages.get(packageName); 7691 oldPkgSetting = mSettings.mPackages.get(packageName); 7692 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 7693 (oldPkgSetting == null)) { 7694 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 7695 return; 7696 } 7697 } 7698 7699 killApplication(packageName, oldPkg.applicationInfo.uid); 7700 7701 res.removedInfo.uid = oldPkg.applicationInfo.uid; 7702 res.removedInfo.removedPackage = packageName; 7703 // Remove existing system package 7704 removePackageLI(oldPkgSetting, true); 7705 // writer 7706 synchronized (mPackages) { 7707 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 7708 // We didn't need to disable the .apk as a current system package, 7709 // which means we are replacing another update that is already 7710 // installed. We need to make sure to delete the older one's .apk. 7711 res.removedInfo.args = createInstallArgs(0, 7712 deletedPackage.applicationInfo.sourceDir, 7713 deletedPackage.applicationInfo.publicSourceDir, 7714 deletedPackage.applicationInfo.nativeLibraryDir); 7715 } else { 7716 res.removedInfo.args = null; 7717 } 7718 } 7719 7720 // Successfully disabled the old package. Now proceed with re-installation 7721 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7722 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7723 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 7724 if (newPackage == null) { 7725 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7726 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7727 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7728 } 7729 } else { 7730 if (newPackage.mExtras != null) { 7731 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 7732 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 7733 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 7734 } 7735 updateSettingsLI(newPackage, installerPackageName, res); 7736 updatedSettings = true; 7737 } 7738 7739 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7740 // Re installation failed. Restore old information 7741 // Remove new pkg information 7742 if (newPackage != null) { 7743 removeInstalledPackageLI(newPackage, true); 7744 } 7745 // Add back the old system package 7746 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 7747 // Restore the old system information in Settings 7748 synchronized(mPackages) { 7749 if (updatedSettings) { 7750 mSettings.enableSystemPackageLPw(packageName); 7751 mSettings.setInstallerPackageName(packageName, 7752 oldPkgSetting.installerPackageName); 7753 } 7754 mSettings.writeLPr(); 7755 } 7756 } 7757 } 7758 7759 // Utility method used to move dex files during install. 7760 private int moveDexFilesLI(PackageParser.Package newPackage) { 7761 int retCode; 7762 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 7763 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath); 7764 if (retCode != 0) { 7765 if (mNoDexOpt) { 7766 /* 7767 * If we're in an engineering build, programs are lazily run 7768 * through dexopt. If the .dex file doesn't exist yet, it 7769 * will be created when the program is run next. 7770 */ 7771 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 7772 } else { 7773 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 7774 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7775 } 7776 } 7777 } 7778 return PackageManager.INSTALL_SUCCEEDED; 7779 } 7780 7781 private void updateSettingsLI(PackageParser.Package newPackage, 7782 String installerPackageName, PackageInstalledInfo res) { 7783 String pkgName = newPackage.packageName; 7784 synchronized (mPackages) { 7785 //write settings. the installStatus will be incomplete at this stage. 7786 //note that the new package setting would have already been 7787 //added to mPackages. It hasn't been persisted yet. 7788 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 7789 mSettings.writeLPr(); 7790 } 7791 7792 if ((res.returnCode = moveDexFilesLI(newPackage)) 7793 != PackageManager.INSTALL_SUCCEEDED) { 7794 // Discontinue if moving dex files failed. 7795 return; 7796 } 7797 7798 Log.d(TAG, "New package installed in " + newPackage.mPath); 7799 7800 synchronized (mPackages) { 7801 updatePermissionsLPw(newPackage.packageName, newPackage, 7802 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 7803 ? UPDATE_PERMISSIONS_ALL : 0)); 7804 res.name = pkgName; 7805 res.uid = newPackage.applicationInfo.uid; 7806 res.pkg = newPackage; 7807 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 7808 mSettings.setInstallerPackageName(pkgName, installerPackageName); 7809 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 7810 //to update install status 7811 mSettings.writeLPr(); 7812 } 7813 } 7814 7815 private void installPackageLI(InstallArgs args, 7816 boolean newInstall, PackageInstalledInfo res) { 7817 int pFlags = args.flags; 7818 String installerPackageName = args.installerPackageName; 7819 File tmpPackageFile = new File(args.getCodePath()); 7820 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 7821 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 7822 boolean replace = false; 7823 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 7824 | (newInstall ? SCAN_NEW_INSTALL : 0); 7825 // Result object to be returned 7826 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 7827 7828 // Retrieve PackageSettings and parse package 7829 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 7830 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 7831 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 7832 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 7833 pp.setSeparateProcesses(mSeparateProcesses); 7834 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 7835 null, mMetrics, parseFlags); 7836 if (pkg == null) { 7837 res.returnCode = pp.getParseError(); 7838 return; 7839 } 7840 String pkgName = res.name = pkg.packageName; 7841 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 7842 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 7843 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 7844 return; 7845 } 7846 } 7847 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) { 7848 res.returnCode = pp.getParseError(); 7849 return; 7850 } 7851 7852 /* If the installer passed in a manifest digest, compare it now. */ 7853 if (args.manifestDigest != null) { 7854 if (DEBUG_INSTALL) { 7855 final String parsedManifest = pkg.manifestDigest == null ? "null" 7856 : pkg.manifestDigest.toString(); 7857 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 7858 + parsedManifest); 7859 } 7860 7861 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 7862 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 7863 return; 7864 } 7865 } else if (DEBUG_INSTALL) { 7866 final String parsedManifest = pkg.manifestDigest == null 7867 ? "null" : pkg.manifestDigest.toString(); 7868 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 7869 } 7870 7871 // Get rid of all references to package scan path via parser. 7872 pp = null; 7873 String oldCodePath = null; 7874 boolean systemApp = false; 7875 synchronized (mPackages) { 7876 // Check if installing already existing package 7877 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 7878 String oldName = mSettings.mRenamedPackages.get(pkgName); 7879 if (pkg.mOriginalPackages != null 7880 && pkg.mOriginalPackages.contains(oldName) 7881 && mPackages.containsKey(oldName)) { 7882 // This package is derived from an original package, 7883 // and this device has been updating from that original 7884 // name. We must continue using the original name, so 7885 // rename the new package here. 7886 pkg.setPackageName(oldName); 7887 pkgName = pkg.packageName; 7888 replace = true; 7889 } else if (mPackages.containsKey(pkgName)) { 7890 // This package, under its official name, already exists 7891 // on the device; we should replace it. 7892 replace = true; 7893 } 7894 } 7895 PackageSetting ps = mSettings.mPackages.get(pkgName); 7896 if (ps != null) { 7897 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 7898 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7899 systemApp = (ps.pkg.applicationInfo.flags & 7900 ApplicationInfo.FLAG_SYSTEM) != 0; 7901 } 7902 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7903 } 7904 } 7905 7906 if (systemApp && onSd) { 7907 // Disable updates to system apps on sdcard 7908 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 7909 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 7910 return; 7911 } 7912 7913 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 7914 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7915 return; 7916 } 7917 // Set application objects path explicitly after the rename 7918 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 7919 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 7920 if (replace) { 7921 replacePackageLI(pkg, parseFlags, scanMode, args.user, 7922 installerPackageName, res); 7923 } else { 7924 installNewPackageLI(pkg, parseFlags, scanMode, args.user, 7925 installerPackageName, res); 7926 } 7927 synchronized (mPackages) { 7928 final PackageSetting ps = mSettings.mPackages.get(pkgName); 7929 if (ps != null) { 7930 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7931 } 7932 } 7933 } 7934 7935 private static boolean isForwardLocked(PackageParser.Package pkg) { 7936 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 7937 } 7938 7939 7940 private boolean isForwardLocked(PackageSetting ps) { 7941 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 7942 } 7943 7944 private static boolean isExternal(PackageParser.Package pkg) { 7945 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 7946 } 7947 7948 private static boolean isExternal(PackageSetting ps) { 7949 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 7950 } 7951 7952 private static boolean isSystemApp(PackageParser.Package pkg) { 7953 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7954 } 7955 7956 private static boolean isSystemApp(ApplicationInfo info) { 7957 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7958 } 7959 7960 private static boolean isSystemApp(PackageSetting ps) { 7961 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 7962 } 7963 7964 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 7965 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 7966 } 7967 7968 private int packageFlagsToInstallFlags(PackageSetting ps) { 7969 int installFlags = 0; 7970 if (isExternal(ps)) { 7971 installFlags |= PackageManager.INSTALL_EXTERNAL; 7972 } 7973 if (isForwardLocked(ps)) { 7974 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 7975 } 7976 return installFlags; 7977 } 7978 7979 private void deleteTempPackageFiles() { 7980 final FilenameFilter filter = new FilenameFilter() { 7981 public boolean accept(File dir, String name) { 7982 return name.startsWith("vmdl") && name.endsWith(".tmp"); 7983 } 7984 }; 7985 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 7986 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 7987 } 7988 7989 private static final void deleteTempPackageFilesInDirectory(File directory, 7990 FilenameFilter filter) { 7991 final String[] tmpFilesList = directory.list(filter); 7992 if (tmpFilesList == null) { 7993 return; 7994 } 7995 for (int i = 0; i < tmpFilesList.length; i++) { 7996 final File tmpFile = new File(directory, tmpFilesList[i]); 7997 tmpFile.delete(); 7998 } 7999 } 8000 8001 private File createTempPackageFile(File installDir) { 8002 File tmpPackageFile; 8003 try { 8004 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 8005 } catch (IOException e) { 8006 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 8007 return null; 8008 } 8009 try { 8010 FileUtils.setPermissions( 8011 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 8012 -1, -1); 8013 if (!SELinux.restorecon(tmpPackageFile)) { 8014 return null; 8015 } 8016 } catch (IOException e) { 8017 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 8018 return null; 8019 } 8020 return tmpPackageFile; 8021 } 8022 8023 public void deletePackage(final String packageName, 8024 final IPackageDeleteObserver observer, 8025 final int flags) { 8026 mContext.enforceCallingOrSelfPermission( 8027 android.Manifest.permission.DELETE_PACKAGES, null); 8028 // Queue up an async operation since the package deletion may take a little while. 8029 final int uid = Binder.getCallingUid(); 8030 mHandler.post(new Runnable() { 8031 public void run() { 8032 mHandler.removeCallbacks(this); 8033 final int returnCode = deletePackageX(packageName, uid, flags); 8034 if (observer != null) { 8035 try { 8036 observer.packageDeleted(packageName, returnCode); 8037 } catch (RemoteException e) { 8038 Log.i(TAG, "Observer no longer exists."); 8039 } //end catch 8040 } //end if 8041 } //end run 8042 }); 8043 } 8044 8045 /** 8046 * This method is an internal method that could be get invoked either 8047 * to delete an installed package or to clean up a failed installation. 8048 * After deleting an installed package, a broadcast is sent to notify any 8049 * listeners that the package has been installed. For cleaning up a failed 8050 * installation, the broadcast is not necessary since the package's 8051 * installation wouldn't have sent the initial broadcast either 8052 * The key steps in deleting a package are 8053 * deleting the package information in internal structures like mPackages, 8054 * deleting the packages base directories through installd 8055 * updating mSettings to reflect current status 8056 * persisting settings for later use 8057 * sending a broadcast if necessary 8058 */ 8059 private int deletePackageX(String packageName, int uid, int flags) { 8060 final PackageRemovedInfo info = new PackageRemovedInfo(); 8061 final boolean res; 8062 8063 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 8064 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 8065 try { 8066 if (dpm != null && dpm.packageHasActiveAdmins(packageName, UserHandle.getUserId(uid))) { 8067 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 8068 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 8069 } 8070 } catch (RemoteException e) { 8071 } 8072 8073 boolean removedForAllUsers = false; 8074 boolean systemUpdate = false; 8075 synchronized (mInstallLock) { 8076 res = deletePackageLI(packageName, 8077 (flags & PackageManager.DELETE_ALL_USERS) != 0 8078 ? UserHandle.ALL : new UserHandle(UserHandle.getUserId(uid)), 8079 true, flags | REMOVE_CHATTY, info, true); 8080 systemUpdate = info.isRemovedPackageSystemUpdate; 8081 if (res && !systemUpdate && mPackages.get(packageName) == null) { 8082 removedForAllUsers = true; 8083 } 8084 } 8085 8086 if (res) { 8087 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 8088 8089 // If the removed package was a system update, the old system package 8090 // was re-enabled; we need to broadcast this information 8091 if (systemUpdate) { 8092 Bundle extras = new Bundle(1); 8093 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 8094 ? info.removedAppId : info.uid); 8095 extras.putBoolean(Intent.EXTRA_REPLACING, true); 8096 8097 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 8098 extras, null, null, null); 8099 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 8100 extras, null, null, null); 8101 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 8102 null, packageName, null, null); 8103 } 8104 } 8105 // Force a gc here. 8106 Runtime.getRuntime().gc(); 8107 // Delete the resources here after sending the broadcast to let 8108 // other processes clean up before deleting resources. 8109 if (info.args != null) { 8110 synchronized (mInstallLock) { 8111 info.args.doPostDeleteLI(true); 8112 } 8113 } 8114 8115 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 8116 } 8117 8118 static class PackageRemovedInfo { 8119 String removedPackage; 8120 int uid = -1; 8121 int removedAppId = -1; 8122 int[] removedUsers = null; 8123 boolean isRemovedPackageSystemUpdate = false; 8124 // Clean up resources deleted packages. 8125 InstallArgs args = null; 8126 8127 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 8128 Bundle extras = new Bundle(1); 8129 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 8130 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 8131 if (replacing) { 8132 extras.putBoolean(Intent.EXTRA_REPLACING, true); 8133 } 8134 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 8135 if (removedPackage != null) { 8136 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 8137 extras, null, null, removedUsers); 8138 if (fullRemove && !replacing) { 8139 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 8140 extras, null, null, removedUsers); 8141 } 8142 } 8143 if (removedAppId >= 0) { 8144 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 8145 removedUsers); 8146 } 8147 } 8148 } 8149 8150 /* 8151 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 8152 * flag is not set, the data directory is removed as well. 8153 * make sure this flag is set for partially installed apps. If not its meaningless to 8154 * delete a partially installed application. 8155 */ 8156 private void removePackageDataLI(PackageSetting ps, PackageRemovedInfo outInfo, 8157 int flags, boolean writeSettings) { 8158 String packageName = ps.name; 8159 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 8160 // Retrieve object to delete permissions for shared user later on 8161 final PackageSetting deletedPs; 8162 // reader 8163 synchronized (mPackages) { 8164 deletedPs = mSettings.mPackages.get(packageName); 8165 if (outInfo != null) { 8166 outInfo.removedPackage = packageName; 8167 outInfo.removedUsers = deletedPs != null 8168 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 8169 : null; 8170 } 8171 } 8172 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 8173 removeDataDirsLI(packageName); 8174 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 8175 } 8176 // writer 8177 synchronized (mPackages) { 8178 if (deletedPs != null) { 8179 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 8180 if (outInfo != null) { 8181 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 8182 } 8183 if (deletedPs != null) { 8184 updatePermissionsLPw(deletedPs.name, null, 0); 8185 if (deletedPs.sharedUser != null) { 8186 // remove permissions associated with package 8187 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 8188 } 8189 } 8190 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 8191 } 8192 } 8193 // can downgrade to reader 8194 if (writeSettings) { 8195 // Save settings now 8196 mSettings.writeLPr(); 8197 } 8198 } 8199 } 8200 8201 /* 8202 * Tries to delete system package. 8203 */ 8204 private boolean deleteSystemPackageLI(PackageSetting newPs, 8205 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 8206 PackageSetting disabledPs = null; 8207 // Confirm if the system package has been updated 8208 // An updated system app can be deleted. This will also have to restore 8209 // the system pkg from system partition 8210 // reader 8211 synchronized (mPackages) { 8212 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 8213 } 8214 if (disabledPs == null) { 8215 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 8216 return false; 8217 } else { 8218 Log.i(TAG, "Deleting system pkg from data partition"); 8219 } 8220 // Delete the updated package 8221 outInfo.isRemovedPackageSystemUpdate = true; 8222 if (disabledPs.versionCode < newPs.versionCode) { 8223 // Delete data for downgrades 8224 flags &= ~PackageManager.DELETE_KEEP_DATA; 8225 } else { 8226 // Preserve data by setting flag 8227 flags |= PackageManager.DELETE_KEEP_DATA; 8228 } 8229 boolean ret = deleteInstalledPackageLI(newPs, true, flags, outInfo, 8230 writeSettings); 8231 if (!ret) { 8232 return false; 8233 } 8234 // writer 8235 synchronized (mPackages) { 8236 // Reinstate the old system package 8237 mSettings.enableSystemPackageLPw(newPs.name); 8238 // Remove any native libraries from the upgraded package. 8239 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 8240 } 8241 // Install the system package 8242 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 8243 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM, 8244 SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 8245 8246 if (newPkg == null) { 8247 Slog.w(TAG, "Failed to restore system package:" + newPs.name 8248 + " with error:" + mLastScanError); 8249 return false; 8250 } 8251 // writer 8252 synchronized (mPackages) { 8253 updatePermissionsLPw(newPkg.packageName, newPkg, 8254 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 8255 // can downgrade to reader here 8256 if (writeSettings) { 8257 mSettings.writeLPr(); 8258 } 8259 } 8260 return true; 8261 } 8262 8263 private boolean deleteInstalledPackageLI(PackageSetting ps, 8264 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo, 8265 boolean writeSettings) { 8266 if (outInfo != null) { 8267 outInfo.uid = ps.appId; 8268 } 8269 8270 // Delete package data from internal structures and also remove data if flag is set 8271 removePackageDataLI(ps, outInfo, flags, writeSettings); 8272 8273 // Delete application code and resources 8274 if (deleteCodeAndResources) { 8275 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 8276 ps.resourcePathString, ps.nativeLibraryPathString); 8277 } 8278 return true; 8279 } 8280 8281 /* 8282 * This method handles package deletion in general 8283 */ 8284 private boolean deletePackageLI(String packageName, UserHandle user, 8285 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo, 8286 boolean writeSettings) { 8287 if (packageName == null) { 8288 Slog.w(TAG, "Attempt to delete null packageName."); 8289 return false; 8290 } 8291 PackageSetting ps; 8292 boolean dataOnly = false; 8293 int removeUser = -1; 8294 int appId = -1; 8295 synchronized (mPackages) { 8296 ps = mSettings.mPackages.get(packageName); 8297 if (ps == null) { 8298 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 8299 return false; 8300 } 8301 if (!isSystemApp(ps) && user != null 8302 && user.getIdentifier() != UserHandle.USER_ALL) { 8303 // The caller is asking that the package only be deleted for a single 8304 // user. To do this, we just mark its uninstalled state and delete 8305 // its data. 8306 ps.setUserState(user.getIdentifier(), 8307 COMPONENT_ENABLED_STATE_DEFAULT, 8308 false, //installed 8309 true, //stopped 8310 true, //notLaunched 8311 null, null); 8312 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 8313 // Other user still have this package installed, so all 8314 // we need to do is clear this user's data and save that 8315 // it is uninstalled. 8316 removeUser = user.getIdentifier(); 8317 appId = ps.appId; 8318 mSettings.writePackageRestrictionsLPr(removeUser); 8319 } else { 8320 // We need to set it back to 'installed' so the uninstall 8321 // broadcasts will be sent correctly. 8322 ps.setInstalled(true, user.getIdentifier()); 8323 } 8324 } 8325 } 8326 8327 if (removeUser >= 0) { 8328 // From above, we determined that we are deleting this only 8329 // for a single user. Continue the work here. 8330 if (outInfo != null) { 8331 outInfo.removedPackage = packageName; 8332 outInfo.removedAppId = appId; 8333 outInfo.removedUsers = new int[] {removeUser}; 8334 } 8335 mInstaller.clearUserData(packageName, removeUser); 8336 schedulePackageCleaning(packageName, removeUser, false); 8337 return true; 8338 } 8339 8340 if (dataOnly) { 8341 // Delete application data first 8342 removePackageDataLI(ps, outInfo, flags, writeSettings); 8343 return true; 8344 } 8345 boolean ret = false; 8346 if (isSystemApp(ps)) { 8347 Log.i(TAG, "Removing system package:" + ps.name); 8348 // When an updated system application is deleted we delete the existing resources as well and 8349 // fall back to existing code in system partition 8350 ret = deleteSystemPackageLI(ps, flags, outInfo, writeSettings); 8351 } else { 8352 Log.i(TAG, "Removing non-system package:" + ps.name); 8353 // Kill application pre-emptively especially for apps on sd. 8354 killApplication(packageName, ps.appId); 8355 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, outInfo, 8356 writeSettings); 8357 } 8358 return ret; 8359 } 8360 8361 private final class ClearStorageConnection implements ServiceConnection { 8362 IMediaContainerService mContainerService; 8363 8364 @Override 8365 public void onServiceConnected(ComponentName name, IBinder service) { 8366 synchronized (this) { 8367 mContainerService = IMediaContainerService.Stub.asInterface(service); 8368 notifyAll(); 8369 } 8370 } 8371 8372 @Override 8373 public void onServiceDisconnected(ComponentName name) { 8374 } 8375 } 8376 8377 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 8378 final boolean mounted; 8379 if (Environment.isExternalStorageEmulated()) { 8380 mounted = true; 8381 } else { 8382 final String status = Environment.getExternalStorageState(); 8383 8384 mounted = status.equals(Environment.MEDIA_MOUNTED) 8385 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 8386 } 8387 8388 if (!mounted) { 8389 return; 8390 } 8391 8392 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 8393 int[] users; 8394 if (userId == UserHandle.USER_ALL) { 8395 users = sUserManager.getUserIds(); 8396 } else { 8397 users = new int[] { userId }; 8398 } 8399 for (int curUser : users) { 8400 ClearStorageConnection conn = new ClearStorageConnection(); 8401 if (mContext.bindService(containerIntent, conn, Context.BIND_AUTO_CREATE, curUser)) { 8402 try { 8403 long timeout = SystemClock.uptimeMillis() + 5000; 8404 synchronized (conn) { 8405 long now = SystemClock.uptimeMillis(); 8406 while (conn.mContainerService == null && now < timeout) { 8407 try { 8408 conn.wait(timeout - now); 8409 } catch (InterruptedException e) { 8410 } 8411 } 8412 } 8413 if (conn.mContainerService == null) { 8414 return; 8415 } 8416 8417 final UserEnvironment userEnv = new UserEnvironment(curUser); 8418 final File externalCacheDir = userEnv 8419 .getExternalStorageAppCacheDirectory(packageName); 8420 try { 8421 conn.mContainerService.clearDirectory(externalCacheDir.toString()); 8422 } catch (RemoteException e) { 8423 } 8424 if (allData) { 8425 final File externalDataDir = userEnv 8426 .getExternalStorageAppDataDirectory(packageName); 8427 try { 8428 conn.mContainerService.clearDirectory(externalDataDir.toString()); 8429 } catch (RemoteException e) { 8430 } 8431 final File externalMediaDir = userEnv 8432 .getExternalStorageAppMediaDirectory(packageName); 8433 try { 8434 conn.mContainerService.clearDirectory(externalMediaDir.toString()); 8435 } catch (RemoteException e) { 8436 } 8437 } 8438 } finally { 8439 mContext.unbindService(conn); 8440 } 8441 } 8442 } 8443 } 8444 8445 @Override 8446 public void clearApplicationUserData(final String packageName, 8447 final IPackageDataObserver observer, final int userId) { 8448 mContext.enforceCallingOrSelfPermission( 8449 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 8450 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 8451 // Queue up an async operation since the package deletion may take a little while. 8452 mHandler.post(new Runnable() { 8453 public void run() { 8454 mHandler.removeCallbacks(this); 8455 final boolean succeeded; 8456 synchronized (mInstallLock) { 8457 succeeded = clearApplicationUserDataLI(packageName, userId); 8458 } 8459 clearExternalStorageDataSync(packageName, userId, true); 8460 if (succeeded) { 8461 // invoke DeviceStorageMonitor's update method to clear any notifications 8462 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) 8463 ServiceManager.getService(DeviceStorageMonitorService.SERVICE); 8464 if (dsm != null) { 8465 dsm.updateMemory(); 8466 } 8467 } 8468 if(observer != null) { 8469 try { 8470 observer.onRemoveCompleted(packageName, succeeded); 8471 } catch (RemoteException e) { 8472 Log.i(TAG, "Observer no longer exists."); 8473 } 8474 } //end if observer 8475 } //end run 8476 }); 8477 } 8478 8479 private boolean clearApplicationUserDataLI(String packageName, int userId) { 8480 if (packageName == null) { 8481 Slog.w(TAG, "Attempt to delete null packageName."); 8482 return false; 8483 } 8484 PackageParser.Package p; 8485 boolean dataOnly = false; 8486 synchronized (mPackages) { 8487 p = mPackages.get(packageName); 8488 if(p == null) { 8489 dataOnly = true; 8490 PackageSetting ps = mSettings.mPackages.get(packageName); 8491 if((ps == null) || (ps.pkg == null)) { 8492 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8493 return false; 8494 } 8495 p = ps.pkg; 8496 } 8497 } 8498 8499 if (!dataOnly) { 8500 //need to check this only for fully installed applications 8501 if (p == null) { 8502 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8503 return false; 8504 } 8505 final ApplicationInfo applicationInfo = p.applicationInfo; 8506 if (applicationInfo == null) { 8507 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8508 return false; 8509 } 8510 } 8511 int retCode = mInstaller.clearUserData(packageName, userId); 8512 if (retCode < 0) { 8513 Slog.w(TAG, "Couldn't remove cache files for package: " 8514 + packageName); 8515 return false; 8516 } 8517 return true; 8518 } 8519 8520 public void deleteApplicationCacheFiles(final String packageName, 8521 final IPackageDataObserver observer) { 8522 mContext.enforceCallingOrSelfPermission( 8523 android.Manifest.permission.DELETE_CACHE_FILES, null); 8524 // Queue up an async operation since the package deletion may take a little while. 8525 final int userId = UserHandle.getCallingUserId(); 8526 mHandler.post(new Runnable() { 8527 public void run() { 8528 mHandler.removeCallbacks(this); 8529 final boolean succeded; 8530 synchronized (mInstallLock) { 8531 succeded = deleteApplicationCacheFilesLI(packageName, userId); 8532 } 8533 clearExternalStorageDataSync(packageName, userId, false); 8534 if(observer != null) { 8535 try { 8536 observer.onRemoveCompleted(packageName, succeded); 8537 } catch (RemoteException e) { 8538 Log.i(TAG, "Observer no longer exists."); 8539 } 8540 } //end if observer 8541 } //end run 8542 }); 8543 } 8544 8545 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 8546 if (packageName == null) { 8547 Slog.w(TAG, "Attempt to delete null packageName."); 8548 return false; 8549 } 8550 PackageParser.Package p; 8551 synchronized (mPackages) { 8552 p = mPackages.get(packageName); 8553 } 8554 if (p == null) { 8555 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8556 return false; 8557 } 8558 final ApplicationInfo applicationInfo = p.applicationInfo; 8559 if (applicationInfo == null) { 8560 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8561 return false; 8562 } 8563 // TODO: Pass userId to deleteCacheFiles 8564 int retCode = mInstaller.deleteCacheFiles(packageName); 8565 if (retCode < 0) { 8566 Slog.w(TAG, "Couldn't remove cache files for package: " 8567 + packageName); 8568 return false; 8569 } 8570 return true; 8571 } 8572 8573 public void getPackageSizeInfo(final String packageName, int userHandle, 8574 final IPackageStatsObserver observer) { 8575 mContext.enforceCallingOrSelfPermission( 8576 android.Manifest.permission.GET_PACKAGE_SIZE, null); 8577 8578 PackageStats stats = new PackageStats(packageName, userHandle); 8579 8580 /* 8581 * Queue up an async operation since the package measurement may take a 8582 * little while. 8583 */ 8584 Message msg = mHandler.obtainMessage(INIT_COPY); 8585 msg.obj = new MeasureParams(stats, observer); 8586 mHandler.sendMessage(msg); 8587 } 8588 8589 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 8590 PackageStats pStats) { 8591 if (packageName == null) { 8592 Slog.w(TAG, "Attempt to get size of null packageName."); 8593 return false; 8594 } 8595 PackageParser.Package p; 8596 boolean dataOnly = false; 8597 String asecPath = null; 8598 synchronized (mPackages) { 8599 p = mPackages.get(packageName); 8600 if(p == null) { 8601 dataOnly = true; 8602 PackageSetting ps = mSettings.mPackages.get(packageName); 8603 if((ps == null) || (ps.pkg == null)) { 8604 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8605 return false; 8606 } 8607 p = ps.pkg; 8608 } 8609 if (p != null && (isExternal(p) || isForwardLocked(p))) { 8610 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 8611 if (secureContainerId != null) { 8612 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 8613 } 8614 } 8615 } 8616 String publicSrcDir = null; 8617 if(!dataOnly) { 8618 final ApplicationInfo applicationInfo = p.applicationInfo; 8619 if (applicationInfo == null) { 8620 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8621 return false; 8622 } 8623 if (isForwardLocked(p)) { 8624 publicSrcDir = applicationInfo.publicSourceDir; 8625 } 8626 } 8627 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, publicSrcDir, 8628 asecPath, pStats); 8629 if (res < 0) { 8630 return false; 8631 } 8632 8633 // Fix-up for forward-locked applications in ASEC containers. 8634 if (!isExternal(p)) { 8635 pStats.codeSize += pStats.externalCodeSize; 8636 pStats.externalCodeSize = 0L; 8637 } 8638 8639 return true; 8640 } 8641 8642 8643 public void addPackageToPreferred(String packageName) { 8644 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 8645 } 8646 8647 public void removePackageFromPreferred(String packageName) { 8648 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 8649 } 8650 8651 public List<PackageInfo> getPreferredPackages(int flags) { 8652 return new ArrayList<PackageInfo>(); 8653 } 8654 8655 private int getUidTargetSdkVersionLockedLPr(int uid) { 8656 Object obj = mSettings.getUserIdLPr(uid); 8657 if (obj instanceof SharedUserSetting) { 8658 final SharedUserSetting sus = (SharedUserSetting) obj; 8659 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 8660 final Iterator<PackageSetting> it = sus.packages.iterator(); 8661 while (it.hasNext()) { 8662 final PackageSetting ps = it.next(); 8663 if (ps.pkg != null) { 8664 int v = ps.pkg.applicationInfo.targetSdkVersion; 8665 if (v < vers) vers = v; 8666 } 8667 } 8668 return vers; 8669 } else if (obj instanceof PackageSetting) { 8670 final PackageSetting ps = (PackageSetting) obj; 8671 if (ps.pkg != null) { 8672 return ps.pkg.applicationInfo.targetSdkVersion; 8673 } 8674 } 8675 return Build.VERSION_CODES.CUR_DEVELOPMENT; 8676 } 8677 8678 public void addPreferredActivity(IntentFilter filter, int match, 8679 ComponentName[] set, ComponentName activity, int userId) { 8680 // writer 8681 int callingUid = Binder.getCallingUid(); 8682 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 8683 synchronized (mPackages) { 8684 if (mContext.checkCallingOrSelfPermission( 8685 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8686 != PackageManager.PERMISSION_GRANTED) { 8687 if (getUidTargetSdkVersionLockedLPr(callingUid) 8688 < Build.VERSION_CODES.FROYO) { 8689 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 8690 + callingUid); 8691 return; 8692 } 8693 mContext.enforceCallingOrSelfPermission( 8694 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8695 } 8696 8697 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 8698 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 8699 mSettings.mPreferredActivities.addFilter( 8700 new PreferredActivity(filter, match, set, activity, userId)); 8701 scheduleWriteSettingsLocked(); 8702 } 8703 } 8704 8705 public void replacePreferredActivity(IntentFilter filter, int match, 8706 ComponentName[] set, ComponentName activity) { 8707 if (filter.countActions() != 1) { 8708 throw new IllegalArgumentException( 8709 "replacePreferredActivity expects filter to have only 1 action."); 8710 } 8711 if (filter.countCategories() != 1) { 8712 throw new IllegalArgumentException( 8713 "replacePreferredActivity expects filter to have only 1 category."); 8714 } 8715 if (filter.countDataAuthorities() != 0 8716 || filter.countDataPaths() != 0 8717 || filter.countDataSchemes() != 0 8718 || filter.countDataTypes() != 0) { 8719 throw new IllegalArgumentException( 8720 "replacePreferredActivity expects filter to have no data authorities, " + 8721 "paths, schemes or types."); 8722 } 8723 synchronized (mPackages) { 8724 if (mContext.checkCallingOrSelfPermission( 8725 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8726 != PackageManager.PERMISSION_GRANTED) { 8727 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 8728 < Build.VERSION_CODES.FROYO) { 8729 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 8730 + Binder.getCallingUid()); 8731 return; 8732 } 8733 mContext.enforceCallingOrSelfPermission( 8734 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8735 } 8736 8737 final int callingUserId = UserHandle.getCallingUserId(); 8738 ArrayList<PreferredActivity> removed = null; 8739 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8740 String action = filter.getAction(0); 8741 String category = filter.getCategory(0); 8742 while (it.hasNext()) { 8743 PreferredActivity pa = it.next(); 8744 if (pa.mUserId != callingUserId) continue; 8745 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) { 8746 if (removed == null) { 8747 removed = new ArrayList<PreferredActivity>(); 8748 } 8749 removed.add(pa); 8750 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":"); 8751 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 8752 } 8753 } 8754 if (removed != null) { 8755 for (int i=0; i<removed.size(); i++) { 8756 PreferredActivity pa = removed.get(i); 8757 mSettings.mPreferredActivities.removeFilter(pa); 8758 } 8759 } 8760 addPreferredActivity(filter, match, set, activity, callingUserId); 8761 } 8762 } 8763 8764 public void clearPackagePreferredActivities(String packageName) { 8765 final int uid = Binder.getCallingUid(); 8766 // writer 8767 synchronized (mPackages) { 8768 PackageParser.Package pkg = mPackages.get(packageName); 8769 if (pkg == null || pkg.applicationInfo.uid != uid) { 8770 if (mContext.checkCallingOrSelfPermission( 8771 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8772 != PackageManager.PERMISSION_GRANTED) { 8773 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 8774 < Build.VERSION_CODES.FROYO) { 8775 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 8776 + Binder.getCallingUid()); 8777 return; 8778 } 8779 mContext.enforceCallingOrSelfPermission( 8780 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8781 } 8782 } 8783 8784 if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) { 8785 scheduleWriteSettingsLocked(); 8786 } 8787 } 8788 } 8789 8790 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 8791 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 8792 ArrayList<PreferredActivity> removed = null; 8793 Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8794 while (it.hasNext()) { 8795 PreferredActivity pa = it.next(); 8796 if (userId != UserHandle.USER_ALL && pa.mUserId != userId) { 8797 continue; 8798 } 8799 if (pa.mPref.mComponent.getPackageName().equals(packageName)) { 8800 if (removed == null) { 8801 removed = new ArrayList<PreferredActivity>(); 8802 } 8803 removed.add(pa); 8804 } 8805 } 8806 if (removed != null) { 8807 for (int i=0; i<removed.size(); i++) { 8808 PreferredActivity pa = removed.get(i); 8809 mSettings.mPreferredActivities.removeFilter(pa); 8810 } 8811 return true; 8812 } 8813 return false; 8814 } 8815 8816 public int getPreferredActivities(List<IntentFilter> outFilters, 8817 List<ComponentName> outActivities, String packageName) { 8818 8819 int num = 0; 8820 final int userId = UserHandle.getCallingUserId(); 8821 // reader 8822 synchronized (mPackages) { 8823 final Iterator<PreferredActivity> it = mSettings.mPreferredActivities.filterIterator(); 8824 while (it.hasNext()) { 8825 final PreferredActivity pa = it.next(); 8826 if (pa.mUserId != userId) { 8827 continue; 8828 } 8829 if (packageName == null 8830 || pa.mPref.mComponent.getPackageName().equals(packageName)) { 8831 if (outFilters != null) { 8832 outFilters.add(new IntentFilter(pa)); 8833 } 8834 if (outActivities != null) { 8835 outActivities.add(pa.mPref.mComponent); 8836 } 8837 } 8838 } 8839 } 8840 8841 return num; 8842 } 8843 8844 @Override 8845 public void setApplicationEnabledSetting(String appPackageName, 8846 int newState, int flags, int userId) { 8847 if (!sUserManager.exists(userId)) return; 8848 setEnabledSetting(appPackageName, null, newState, flags, userId); 8849 } 8850 8851 @Override 8852 public void setComponentEnabledSetting(ComponentName componentName, 8853 int newState, int flags, int userId) { 8854 if (!sUserManager.exists(userId)) return; 8855 setEnabledSetting(componentName.getPackageName(), 8856 componentName.getClassName(), newState, flags, userId); 8857 } 8858 8859 private void setEnabledSetting( 8860 final String packageName, String className, int newState, final int flags, int userId) { 8861 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 8862 || newState == COMPONENT_ENABLED_STATE_ENABLED 8863 || newState == COMPONENT_ENABLED_STATE_DISABLED 8864 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) { 8865 throw new IllegalArgumentException("Invalid new component state: " 8866 + newState); 8867 } 8868 PackageSetting pkgSetting; 8869 final int uid = Binder.getCallingUid(); 8870 final int permission = mContext.checkCallingPermission( 8871 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 8872 enforceCrossUserPermission(uid, userId, false, "set enabled"); 8873 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 8874 boolean sendNow = false; 8875 boolean isApp = (className == null); 8876 String componentName = isApp ? packageName : className; 8877 int packageUid = -1; 8878 ArrayList<String> components; 8879 8880 // writer 8881 synchronized (mPackages) { 8882 pkgSetting = mSettings.mPackages.get(packageName); 8883 if (pkgSetting == null) { 8884 if (className == null) { 8885 throw new IllegalArgumentException( 8886 "Unknown package: " + packageName); 8887 } 8888 throw new IllegalArgumentException( 8889 "Unknown component: " + packageName 8890 + "/" + className); 8891 } 8892 // Allow root and verify that userId is not being specified by a different user 8893 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 8894 throw new SecurityException( 8895 "Permission Denial: attempt to change component state from pid=" 8896 + Binder.getCallingPid() 8897 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 8898 } 8899 if (className == null) { 8900 // We're dealing with an application/package level state change 8901 if (pkgSetting.getEnabled(userId) == newState) { 8902 // Nothing to do 8903 return; 8904 } 8905 pkgSetting.setEnabled(newState, userId); 8906 // pkgSetting.pkg.mSetEnabled = newState; 8907 } else { 8908 // We're dealing with a component level state change 8909 // First, verify that this is a valid class name. 8910 PackageParser.Package pkg = pkgSetting.pkg; 8911 if (pkg == null || !pkg.hasComponentClassName(className)) { 8912 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 8913 throw new IllegalArgumentException("Component class " + className 8914 + " does not exist in " + packageName); 8915 } else { 8916 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 8917 + className + " does not exist in " + packageName); 8918 } 8919 } 8920 switch (newState) { 8921 case COMPONENT_ENABLED_STATE_ENABLED: 8922 if (!pkgSetting.enableComponentLPw(className, userId)) { 8923 return; 8924 } 8925 break; 8926 case COMPONENT_ENABLED_STATE_DISABLED: 8927 if (!pkgSetting.disableComponentLPw(className, userId)) { 8928 return; 8929 } 8930 break; 8931 case COMPONENT_ENABLED_STATE_DEFAULT: 8932 if (!pkgSetting.restoreComponentLPw(className, userId)) { 8933 return; 8934 } 8935 break; 8936 default: 8937 Slog.e(TAG, "Invalid new component state: " + newState); 8938 return; 8939 } 8940 } 8941 mSettings.writePackageRestrictionsLPr(userId); 8942 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 8943 components = mPendingBroadcasts.get(packageName); 8944 final boolean newPackage = components == null; 8945 if (newPackage) { 8946 components = new ArrayList<String>(); 8947 } 8948 if (!components.contains(componentName)) { 8949 components.add(componentName); 8950 } 8951 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 8952 sendNow = true; 8953 // Purge entry from pending broadcast list if another one exists already 8954 // since we are sending one right away. 8955 mPendingBroadcasts.remove(packageName); 8956 } else { 8957 if (newPackage) { 8958 mPendingBroadcasts.put(packageName, components); 8959 } 8960 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 8961 // Schedule a message 8962 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 8963 } 8964 } 8965 } 8966 8967 long callingId = Binder.clearCallingIdentity(); 8968 try { 8969 if (sendNow) { 8970 sendPackageChangedBroadcast(packageName, 8971 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 8972 } 8973 } finally { 8974 Binder.restoreCallingIdentity(callingId); 8975 } 8976 } 8977 8978 private void sendPackageChangedBroadcast(String packageName, 8979 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 8980 if (DEBUG_INSTALL) 8981 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 8982 + componentNames); 8983 Bundle extras = new Bundle(4); 8984 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 8985 String nameList[] = new String[componentNames.size()]; 8986 componentNames.toArray(nameList); 8987 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 8988 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 8989 extras.putInt(Intent.EXTRA_UID, packageUid); 8990 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 8991 new int[] {UserHandle.getUserId(packageUid)}); 8992 } 8993 8994 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 8995 if (!sUserManager.exists(userId)) return; 8996 final int uid = Binder.getCallingUid(); 8997 final int permission = mContext.checkCallingOrSelfPermission( 8998 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 8999 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 9000 enforceCrossUserPermission(uid, userId, true, "stop package"); 9001 // writer 9002 synchronized (mPackages) { 9003 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 9004 uid, userId)) { 9005 scheduleWritePackageRestrictionsLocked(userId); 9006 } 9007 } 9008 } 9009 9010 public String getInstallerPackageName(String packageName) { 9011 // reader 9012 synchronized (mPackages) { 9013 return mSettings.getInstallerPackageNameLPr(packageName); 9014 } 9015 } 9016 9017 @Override 9018 public int getApplicationEnabledSetting(String packageName, int userId) { 9019 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 9020 int uid = Binder.getCallingUid(); 9021 enforceCrossUserPermission(uid, userId, false, "get enabled"); 9022 // reader 9023 synchronized (mPackages) { 9024 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 9025 } 9026 } 9027 9028 @Override 9029 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 9030 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 9031 int uid = Binder.getCallingUid(); 9032 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 9033 // reader 9034 synchronized (mPackages) { 9035 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 9036 } 9037 } 9038 9039 public void enterSafeMode() { 9040 enforceSystemOrRoot("Only the system can request entering safe mode"); 9041 9042 if (!mSystemReady) { 9043 mSafeMode = true; 9044 } 9045 } 9046 9047 public void systemReady() { 9048 mSystemReady = true; 9049 9050 // Read the compatibilty setting when the system is ready. 9051 boolean compatibilityModeEnabled = android.provider.Settings.System.getInt( 9052 mContext.getContentResolver(), 9053 android.provider.Settings.System.COMPATIBILITY_MODE, 1) == 1; 9054 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 9055 if (DEBUG_SETTINGS) { 9056 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 9057 } 9058 } 9059 9060 public boolean isSafeMode() { 9061 return mSafeMode; 9062 } 9063 9064 public boolean hasSystemUidErrors() { 9065 return mHasSystemUidErrors; 9066 } 9067 9068 static String arrayToString(int[] array) { 9069 StringBuffer buf = new StringBuffer(128); 9070 buf.append('['); 9071 if (array != null) { 9072 for (int i=0; i<array.length; i++) { 9073 if (i > 0) buf.append(", "); 9074 buf.append(array[i]); 9075 } 9076 } 9077 buf.append(']'); 9078 return buf.toString(); 9079 } 9080 9081 static class DumpState { 9082 public static final int DUMP_LIBS = 1 << 0; 9083 9084 public static final int DUMP_FEATURES = 1 << 1; 9085 9086 public static final int DUMP_RESOLVERS = 1 << 2; 9087 9088 public static final int DUMP_PERMISSIONS = 1 << 3; 9089 9090 public static final int DUMP_PACKAGES = 1 << 4; 9091 9092 public static final int DUMP_SHARED_USERS = 1 << 5; 9093 9094 public static final int DUMP_MESSAGES = 1 << 6; 9095 9096 public static final int DUMP_PROVIDERS = 1 << 7; 9097 9098 public static final int DUMP_VERIFIERS = 1 << 8; 9099 9100 public static final int DUMP_PREFERRED = 1 << 9; 9101 9102 public static final int DUMP_PREFERRED_XML = 1 << 10; 9103 9104 public static final int OPTION_SHOW_FILTERS = 1 << 0; 9105 9106 private int mTypes; 9107 9108 private int mOptions; 9109 9110 private boolean mTitlePrinted; 9111 9112 private SharedUserSetting mSharedUser; 9113 9114 public boolean isDumping(int type) { 9115 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 9116 return true; 9117 } 9118 9119 return (mTypes & type) != 0; 9120 } 9121 9122 public void setDump(int type) { 9123 mTypes |= type; 9124 } 9125 9126 public boolean isOptionEnabled(int option) { 9127 return (mOptions & option) != 0; 9128 } 9129 9130 public void setOptionEnabled(int option) { 9131 mOptions |= option; 9132 } 9133 9134 public boolean onTitlePrinted() { 9135 final boolean printed = mTitlePrinted; 9136 mTitlePrinted = true; 9137 return printed; 9138 } 9139 9140 public boolean getTitlePrinted() { 9141 return mTitlePrinted; 9142 } 9143 9144 public void setTitlePrinted(boolean enabled) { 9145 mTitlePrinted = enabled; 9146 } 9147 9148 public SharedUserSetting getSharedUser() { 9149 return mSharedUser; 9150 } 9151 9152 public void setSharedUser(SharedUserSetting user) { 9153 mSharedUser = user; 9154 } 9155 } 9156 9157 @Override 9158 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9159 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 9160 != PackageManager.PERMISSION_GRANTED) { 9161 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 9162 + Binder.getCallingPid() 9163 + ", uid=" + Binder.getCallingUid() 9164 + " without permission " 9165 + android.Manifest.permission.DUMP); 9166 return; 9167 } 9168 9169 DumpState dumpState = new DumpState(); 9170 9171 String packageName = null; 9172 9173 int opti = 0; 9174 while (opti < args.length) { 9175 String opt = args[opti]; 9176 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 9177 break; 9178 } 9179 opti++; 9180 if ("-a".equals(opt)) { 9181 // Right now we only know how to print all. 9182 } else if ("-h".equals(opt)) { 9183 pw.println("Package manager dump options:"); 9184 pw.println(" [-h] [-f] [cmd] ..."); 9185 pw.println(" -f: print details of intent filters"); 9186 pw.println(" -h: print this help"); 9187 pw.println(" cmd may be one of:"); 9188 pw.println(" l[ibraries]: list known shared libraries"); 9189 pw.println(" f[ibraries]: list device features"); 9190 pw.println(" r[esolvers]: dump intent resolvers"); 9191 pw.println(" perm[issions]: dump permissions"); 9192 pw.println(" pref[erred]: print preferred package settings"); 9193 pw.println(" preferred-xml: print preferred package settings as xml"); 9194 pw.println(" prov[iders]: dump content providers"); 9195 pw.println(" p[ackages]: dump installed packages"); 9196 pw.println(" s[hared-users]: dump shared user IDs"); 9197 pw.println(" m[essages]: print collected runtime messages"); 9198 pw.println(" v[erifiers]: print package verifier info"); 9199 pw.println(" <package.name>: info about given package"); 9200 return; 9201 } else if ("-f".equals(opt)) { 9202 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 9203 } else { 9204 pw.println("Unknown argument: " + opt + "; use -h for help"); 9205 } 9206 } 9207 9208 // Is the caller requesting to dump a particular piece of data? 9209 if (opti < args.length) { 9210 String cmd = args[opti]; 9211 opti++; 9212 // Is this a package name? 9213 if ("android".equals(cmd) || cmd.contains(".")) { 9214 packageName = cmd; 9215 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 9216 dumpState.setDump(DumpState.DUMP_LIBS); 9217 } else if ("f".equals(cmd) || "features".equals(cmd)) { 9218 dumpState.setDump(DumpState.DUMP_FEATURES); 9219 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 9220 dumpState.setDump(DumpState.DUMP_RESOLVERS); 9221 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 9222 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 9223 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 9224 dumpState.setDump(DumpState.DUMP_PREFERRED); 9225 } else if ("preferred-xml".equals(cmd)) { 9226 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 9227 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 9228 dumpState.setDump(DumpState.DUMP_PACKAGES); 9229 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 9230 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 9231 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 9232 dumpState.setDump(DumpState.DUMP_PROVIDERS); 9233 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 9234 dumpState.setDump(DumpState.DUMP_MESSAGES); 9235 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 9236 dumpState.setDump(DumpState.DUMP_VERIFIERS); 9237 } 9238 } 9239 9240 // reader 9241 synchronized (mPackages) { 9242 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 9243 if (dumpState.onTitlePrinted()) 9244 pw.println(" "); 9245 pw.println("Verifiers:"); 9246 pw.print(" Required: "); 9247 pw.print(mRequiredVerifierPackage); 9248 pw.print(" (uid="); 9249 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 9250 pw.println(")"); 9251 } 9252 9253 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 9254 if (dumpState.onTitlePrinted()) 9255 pw.println(" "); 9256 pw.println("Libraries:"); 9257 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 9258 while (it.hasNext()) { 9259 String name = it.next(); 9260 pw.print(" "); 9261 pw.print(name); 9262 pw.print(" -> "); 9263 pw.println(mSharedLibraries.get(name)); 9264 } 9265 } 9266 9267 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 9268 if (dumpState.onTitlePrinted()) 9269 pw.println(" "); 9270 pw.println("Features:"); 9271 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 9272 while (it.hasNext()) { 9273 String name = it.next(); 9274 pw.print(" "); 9275 pw.println(name); 9276 } 9277 } 9278 9279 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 9280 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 9281 : "Activity Resolver Table:", " ", packageName, 9282 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9283 dumpState.setTitlePrinted(true); 9284 } 9285 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 9286 : "Receiver Resolver Table:", " ", packageName, 9287 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9288 dumpState.setTitlePrinted(true); 9289 } 9290 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 9291 : "Service Resolver Table:", " ", packageName, 9292 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9293 dumpState.setTitlePrinted(true); 9294 } 9295 } 9296 9297 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 9298 if (mSettings.mPreferredActivities.dump(pw, 9299 dumpState.getTitlePrinted() ? "\nPreferred Activities:" 9300 : "Preferred Activities:", " ", 9301 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9302 dumpState.setTitlePrinted(true); 9303 } 9304 } 9305 9306 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 9307 pw.flush(); 9308 FileOutputStream fout = new FileOutputStream(fd); 9309 BufferedOutputStream str = new BufferedOutputStream(fout); 9310 XmlSerializer serializer = new FastXmlSerializer(); 9311 try { 9312 serializer.setOutput(str, "utf-8"); 9313 serializer.startDocument(null, true); 9314 serializer.setFeature( 9315 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 9316 mSettings.writePreferredActivitiesLPr(serializer); 9317 serializer.endDocument(); 9318 serializer.flush(); 9319 } catch (IllegalArgumentException e) { 9320 pw.println("Failed writing: " + e); 9321 } catch (IllegalStateException e) { 9322 pw.println("Failed writing: " + e); 9323 } catch (IOException e) { 9324 pw.println("Failed writing: " + e); 9325 } 9326 } 9327 9328 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 9329 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 9330 } 9331 9332 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 9333 boolean printedSomething = false; 9334 for (PackageParser.Provider p : mProvidersByComponent.values()) { 9335 if (packageName != null && !packageName.equals(p.info.packageName)) { 9336 continue; 9337 } 9338 if (!printedSomething) { 9339 if (dumpState.onTitlePrinted()) 9340 pw.println(" "); 9341 pw.println("Registered ContentProviders:"); 9342 printedSomething = true; 9343 } 9344 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":"); 9345 pw.print(" "); pw.println(p.toString()); 9346 } 9347 printedSomething = false; 9348 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) { 9349 PackageParser.Provider p = entry.getValue(); 9350 if (packageName != null && !packageName.equals(p.info.packageName)) { 9351 continue; 9352 } 9353 if (!printedSomething) { 9354 if (dumpState.onTitlePrinted()) 9355 pw.println(" "); 9356 pw.println("ContentProvider Authorities:"); 9357 printedSomething = true; 9358 } 9359 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 9360 pw.print(" "); pw.println(p.toString()); 9361 if (p.info != null && p.info.applicationInfo != null) { 9362 final String appInfo = p.info.applicationInfo.toString(); 9363 pw.print(" applicationInfo="); pw.println(appInfo); 9364 } 9365 } 9366 } 9367 9368 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 9369 mSettings.dumpPackagesLPr(pw, packageName, dumpState); 9370 } 9371 9372 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 9373 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 9374 } 9375 9376 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 9377 if (dumpState.onTitlePrinted()) 9378 pw.println(" "); 9379 mSettings.dumpReadMessagesLPr(pw, dumpState); 9380 9381 pw.println(" "); 9382 pw.println("Package warning messages:"); 9383 final File fname = getSettingsProblemFile(); 9384 FileInputStream in = null; 9385 try { 9386 in = new FileInputStream(fname); 9387 final int avail = in.available(); 9388 final byte[] data = new byte[avail]; 9389 in.read(data); 9390 pw.print(new String(data)); 9391 } catch (FileNotFoundException e) { 9392 } catch (IOException e) { 9393 } finally { 9394 if (in != null) { 9395 try { 9396 in.close(); 9397 } catch (IOException e) { 9398 } 9399 } 9400 } 9401 } 9402 } 9403 } 9404 9405 // ------- apps on sdcard specific code ------- 9406 static final boolean DEBUG_SD_INSTALL = false; 9407 9408 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 9409 9410 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 9411 9412 private boolean mMediaMounted = false; 9413 9414 private String getEncryptKey() { 9415 try { 9416 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 9417 SD_ENCRYPTION_KEYSTORE_NAME); 9418 if (sdEncKey == null) { 9419 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 9420 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 9421 if (sdEncKey == null) { 9422 Slog.e(TAG, "Failed to create encryption keys"); 9423 return null; 9424 } 9425 } 9426 return sdEncKey; 9427 } catch (NoSuchAlgorithmException nsae) { 9428 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 9429 return null; 9430 } catch (IOException ioe) { 9431 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 9432 return null; 9433 } 9434 9435 } 9436 9437 /* package */static String getTempContainerId() { 9438 int tmpIdx = 1; 9439 String list[] = PackageHelper.getSecureContainerList(); 9440 if (list != null) { 9441 for (final String name : list) { 9442 // Ignore null and non-temporary container entries 9443 if (name == null || !name.startsWith(mTempContainerPrefix)) { 9444 continue; 9445 } 9446 9447 String subStr = name.substring(mTempContainerPrefix.length()); 9448 try { 9449 int cid = Integer.parseInt(subStr); 9450 if (cid >= tmpIdx) { 9451 tmpIdx = cid + 1; 9452 } 9453 } catch (NumberFormatException e) { 9454 } 9455 } 9456 } 9457 return mTempContainerPrefix + tmpIdx; 9458 } 9459 9460 /* 9461 * Update media status on PackageManager. 9462 */ 9463 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 9464 int callingUid = Binder.getCallingUid(); 9465 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 9466 throw new SecurityException("Media status can only be updated by the system"); 9467 } 9468 // reader; this apparently protects mMediaMounted, but should probably 9469 // be a different lock in that case. 9470 synchronized (mPackages) { 9471 Log.i(TAG, "Updating external media status from " 9472 + (mMediaMounted ? "mounted" : "unmounted") + " to " 9473 + (mediaStatus ? "mounted" : "unmounted")); 9474 if (DEBUG_SD_INSTALL) 9475 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 9476 + ", mMediaMounted=" + mMediaMounted); 9477 if (mediaStatus == mMediaMounted) { 9478 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 9479 : 0, -1); 9480 mHandler.sendMessage(msg); 9481 return; 9482 } 9483 mMediaMounted = mediaStatus; 9484 } 9485 // Queue up an async operation since the package installation may take a 9486 // little while. 9487 mHandler.post(new Runnable() { 9488 public void run() { 9489 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 9490 } 9491 }); 9492 } 9493 9494 /** 9495 * Called by MountService when the initial ASECs to scan are available. 9496 * Should block until all the ASEC containers are finished being scanned. 9497 */ 9498 public void scanAvailableAsecs() { 9499 updateExternalMediaStatusInner(true, false, false); 9500 } 9501 9502 /* 9503 * Collect information of applications on external media, map them against 9504 * existing containers and update information based on current mount status. 9505 * Please note that we always have to report status if reportStatus has been 9506 * set to true especially when unloading packages. 9507 */ 9508 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 9509 boolean externalStorage) { 9510 // Collection of uids 9511 int uidArr[] = null; 9512 // Collection of stale containers 9513 HashSet<String> removeCids = new HashSet<String>(); 9514 // Collection of packages on external media with valid containers. 9515 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 9516 // Get list of secure containers. 9517 final String list[] = PackageHelper.getSecureContainerList(); 9518 if (list == null || list.length == 0) { 9519 Log.i(TAG, "No secure containers on sdcard"); 9520 } else { 9521 // Process list of secure containers and categorize them 9522 // as active or stale based on their package internal state. 9523 int uidList[] = new int[list.length]; 9524 int num = 0; 9525 // reader 9526 synchronized (mPackages) { 9527 for (String cid : list) { 9528 if (DEBUG_SD_INSTALL) 9529 Log.i(TAG, "Processing container " + cid); 9530 String pkgName = getAsecPackageName(cid); 9531 if (pkgName == null) { 9532 if (DEBUG_SD_INSTALL) 9533 Log.i(TAG, "Container : " + cid + " stale"); 9534 removeCids.add(cid); 9535 continue; 9536 } 9537 if (DEBUG_SD_INSTALL) 9538 Log.i(TAG, "Looking for pkg : " + pkgName); 9539 9540 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9541 if (ps == null) { 9542 Log.i(TAG, "Deleting container with no matching settings " + cid); 9543 removeCids.add(cid); 9544 continue; 9545 } 9546 9547 /* 9548 * Skip packages that are not external if we're unmounting 9549 * external storage. 9550 */ 9551 if (externalStorage && !isMounted && !isExternal(ps)) { 9552 continue; 9553 } 9554 9555 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps)); 9556 // The package status is changed only if the code path 9557 // matches between settings and the container id. 9558 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 9559 if (DEBUG_SD_INSTALL) { 9560 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 9561 + " at code path: " + ps.codePathString); 9562 } 9563 9564 // We do have a valid package installed on sdcard 9565 processCids.put(args, ps.codePathString); 9566 final int uid = ps.appId; 9567 if (uid != -1) { 9568 uidList[num++] = uid; 9569 } 9570 } else { 9571 Log.i(TAG, "Deleting stale container for " + cid); 9572 removeCids.add(cid); 9573 } 9574 } 9575 } 9576 9577 if (num > 0) { 9578 // Sort uid list 9579 Arrays.sort(uidList, 0, num); 9580 // Throw away duplicates 9581 uidArr = new int[num]; 9582 uidArr[0] = uidList[0]; 9583 int di = 0; 9584 for (int i = 1; i < num; i++) { 9585 if (uidList[i - 1] != uidList[i]) { 9586 uidArr[di++] = uidList[i]; 9587 } 9588 } 9589 } 9590 } 9591 // Process packages with valid entries. 9592 if (isMounted) { 9593 if (DEBUG_SD_INSTALL) 9594 Log.i(TAG, "Loading packages"); 9595 loadMediaPackages(processCids, uidArr, removeCids); 9596 startCleaningPackages(-1); 9597 } else { 9598 if (DEBUG_SD_INSTALL) 9599 Log.i(TAG, "Unloading packages"); 9600 unloadMediaPackages(processCids, uidArr, reportStatus); 9601 } 9602 } 9603 9604 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList, 9605 int uidArr[], IIntentReceiver finishedReceiver) { 9606 int size = pkgList.size(); 9607 if (size > 0) { 9608 // Send broadcasts here 9609 Bundle extras = new Bundle(); 9610 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 9611 .toArray(new String[size])); 9612 if (uidArr != null) { 9613 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 9614 } 9615 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 9616 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 9617 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 9618 } 9619 } 9620 9621 /* 9622 * Look at potentially valid container ids from processCids If package 9623 * information doesn't match the one on record or package scanning fails, 9624 * the cid is added to list of removeCids. We currently don't delete stale 9625 * containers. 9626 */ 9627 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 9628 HashSet<String> removeCids) { 9629 ArrayList<String> pkgList = new ArrayList<String>(); 9630 Set<AsecInstallArgs> keys = processCids.keySet(); 9631 boolean doGc = false; 9632 for (AsecInstallArgs args : keys) { 9633 String codePath = processCids.get(args); 9634 if (DEBUG_SD_INSTALL) 9635 Log.i(TAG, "Loading container : " + args.cid); 9636 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9637 try { 9638 // Make sure there are no container errors first. 9639 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 9640 Slog.e(TAG, "Failed to mount cid : " + args.cid 9641 + " when installing from sdcard"); 9642 continue; 9643 } 9644 // Check code path here. 9645 if (codePath == null || !codePath.equals(args.getCodePath())) { 9646 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 9647 + " does not match one in settings " + codePath); 9648 continue; 9649 } 9650 // Parse package 9651 int parseFlags = mDefParseFlags; 9652 if (args.isExternal()) { 9653 parseFlags |= PackageParser.PARSE_ON_SDCARD; 9654 } 9655 if (args.isFwdLocked()) { 9656 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 9657 } 9658 9659 doGc = true; 9660 synchronized (mInstallLock) { 9661 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 9662 0, 0, null); 9663 // Scan the package 9664 if (pkg != null) { 9665 /* 9666 * TODO why is the lock being held? doPostInstall is 9667 * called in other places without the lock. This needs 9668 * to be straightened out. 9669 */ 9670 // writer 9671 synchronized (mPackages) { 9672 retCode = PackageManager.INSTALL_SUCCEEDED; 9673 pkgList.add(pkg.packageName); 9674 // Post process args 9675 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 9676 pkg.applicationInfo.uid); 9677 } 9678 } else { 9679 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 9680 } 9681 } 9682 9683 } finally { 9684 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 9685 // Don't destroy container here. Wait till gc clears things 9686 // up. 9687 removeCids.add(args.cid); 9688 } 9689 } 9690 } 9691 // writer 9692 synchronized (mPackages) { 9693 // If the platform SDK has changed since the last time we booted, 9694 // we need to re-grant app permission to catch any new ones that 9695 // appear. This is really a hack, and means that apps can in some 9696 // cases get permissions that the user didn't initially explicitly 9697 // allow... it would be nice to have some better way to handle 9698 // this situation. 9699 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 9700 if (regrantPermissions) 9701 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 9702 + mSdkVersion + "; regranting permissions for external storage"); 9703 mSettings.mExternalSdkPlatform = mSdkVersion; 9704 9705 // Make sure group IDs have been assigned, and any permission 9706 // changes in other apps are accounted for 9707 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 9708 | (regrantPermissions 9709 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 9710 : 0)); 9711 // can downgrade to reader 9712 // Persist settings 9713 mSettings.writeLPr(); 9714 } 9715 // Send a broadcast to let everyone know we are done processing 9716 if (pkgList.size() > 0) { 9717 sendResourcesChangedBroadcast(true, pkgList, uidArr, null); 9718 } 9719 // Force gc to avoid any stale parser references that we might have. 9720 if (doGc) { 9721 Runtime.getRuntime().gc(); 9722 } 9723 // List stale containers and destroy stale temporary containers. 9724 if (removeCids != null) { 9725 for (String cid : removeCids) { 9726 if (cid.startsWith(mTempContainerPrefix)) { 9727 Log.i(TAG, "Destroying stale temporary container " + cid); 9728 PackageHelper.destroySdDir(cid); 9729 } else { 9730 Log.w(TAG, "Container " + cid + " is stale"); 9731 } 9732 } 9733 } 9734 } 9735 9736 /* 9737 * Utility method to unload a list of specified containers 9738 */ 9739 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 9740 // Just unmount all valid containers. 9741 for (AsecInstallArgs arg : cidArgs) { 9742 synchronized (mInstallLock) { 9743 arg.doPostDeleteLI(false); 9744 } 9745 } 9746 } 9747 9748 /* 9749 * Unload packages mounted on external media. This involves deleting package 9750 * data from internal structures, sending broadcasts about diabled packages, 9751 * gc'ing to free up references, unmounting all secure containers 9752 * corresponding to packages on external media, and posting a 9753 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 9754 * that we always have to post this message if status has been requested no 9755 * matter what. 9756 */ 9757 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 9758 final boolean reportStatus) { 9759 if (DEBUG_SD_INSTALL) 9760 Log.i(TAG, "unloading media packages"); 9761 ArrayList<String> pkgList = new ArrayList<String>(); 9762 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 9763 final Set<AsecInstallArgs> keys = processCids.keySet(); 9764 for (AsecInstallArgs args : keys) { 9765 String pkgName = args.getPackageName(); 9766 if (DEBUG_SD_INSTALL) 9767 Log.i(TAG, "Trying to unload pkg : " + pkgName); 9768 // Delete package internally 9769 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 9770 synchronized (mInstallLock) { 9771 boolean res = deletePackageLI(pkgName, null, false, 9772 PackageManager.DELETE_KEEP_DATA, outInfo, false); 9773 if (res) { 9774 pkgList.add(pkgName); 9775 } else { 9776 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 9777 failedList.add(args); 9778 } 9779 } 9780 } 9781 9782 // reader 9783 synchronized (mPackages) { 9784 // We didn't update the settings after removing each package; 9785 // write them now for all packages. 9786 mSettings.writeLPr(); 9787 } 9788 9789 // We have to absolutely send UPDATED_MEDIA_STATUS only 9790 // after confirming that all the receivers processed the ordered 9791 // broadcast when packages get disabled, force a gc to clean things up. 9792 // and unload all the containers. 9793 if (pkgList.size() > 0) { 9794 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() { 9795 public void performReceive(Intent intent, int resultCode, String data, 9796 Bundle extras, boolean ordered, boolean sticky, 9797 int sendingUser) throws RemoteException { 9798 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 9799 reportStatus ? 1 : 0, 1, keys); 9800 mHandler.sendMessage(msg); 9801 } 9802 }); 9803 } else { 9804 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 9805 keys); 9806 mHandler.sendMessage(msg); 9807 } 9808 } 9809 9810 /** Binder call */ 9811 @Override 9812 public void movePackage(final String packageName, final IPackageMoveObserver observer, 9813 final int flags) { 9814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 9815 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 9816 int returnCode = PackageManager.MOVE_SUCCEEDED; 9817 int currFlags = 0; 9818 int newFlags = 0; 9819 // reader 9820 synchronized (mPackages) { 9821 PackageParser.Package pkg = mPackages.get(packageName); 9822 if (pkg == null) { 9823 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9824 } else { 9825 // Disable moving fwd locked apps and system packages 9826 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 9827 Slog.w(TAG, "Cannot move system application"); 9828 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 9829 } else if (pkg.mOperationPending) { 9830 Slog.w(TAG, "Attempt to move package which has pending operations"); 9831 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 9832 } else { 9833 // Find install location first 9834 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 9835 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 9836 Slog.w(TAG, "Ambigous flags specified for move location."); 9837 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9838 } else { 9839 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 9840 : PackageManager.INSTALL_INTERNAL; 9841 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 9842 : PackageManager.INSTALL_INTERNAL; 9843 9844 if (newFlags == currFlags) { 9845 Slog.w(TAG, "No move required. Trying to move to same location"); 9846 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9847 } else { 9848 if (isForwardLocked(pkg)) { 9849 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9850 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9851 } 9852 } 9853 } 9854 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9855 pkg.mOperationPending = true; 9856 } 9857 } 9858 } 9859 9860 /* 9861 * TODO this next block probably shouldn't be inside the lock. We 9862 * can't guarantee these won't change after this is fired off 9863 * anyway. 9864 */ 9865 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 9866 processPendingMove(new MoveParams(null, observer, 0, packageName, 9867 null, -1, user), 9868 returnCode); 9869 } else { 9870 Message msg = mHandler.obtainMessage(INIT_COPY); 9871 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 9872 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir); 9873 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 9874 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user); 9875 msg.obj = mp; 9876 mHandler.sendMessage(msg); 9877 } 9878 } 9879 } 9880 9881 private void processPendingMove(final MoveParams mp, final int currentStatus) { 9882 // Queue up an async operation since the package deletion may take a 9883 // little while. 9884 mHandler.post(new Runnable() { 9885 public void run() { 9886 // TODO fix this; this does nothing. 9887 mHandler.removeCallbacks(this); 9888 int returnCode = currentStatus; 9889 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 9890 int uidArr[] = null; 9891 ArrayList<String> pkgList = null; 9892 synchronized (mPackages) { 9893 PackageParser.Package pkg = mPackages.get(mp.packageName); 9894 if (pkg == null) { 9895 Slog.w(TAG, " Package " + mp.packageName 9896 + " doesn't exist. Aborting move"); 9897 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9898 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 9899 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 9900 + mp.srcArgs.getCodePath() + " to " 9901 + pkg.applicationInfo.sourceDir 9902 + " Aborting move and returning error"); 9903 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9904 } else { 9905 uidArr = new int[] { 9906 pkg.applicationInfo.uid 9907 }; 9908 pkgList = new ArrayList<String>(); 9909 pkgList.add(mp.packageName); 9910 } 9911 } 9912 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9913 // Send resources unavailable broadcast 9914 sendResourcesChangedBroadcast(false, pkgList, uidArr, null); 9915 // Update package code and resource paths 9916 synchronized (mInstallLock) { 9917 synchronized (mPackages) { 9918 PackageParser.Package pkg = mPackages.get(mp.packageName); 9919 // Recheck for package again. 9920 if (pkg == null) { 9921 Slog.w(TAG, " Package " + mp.packageName 9922 + " doesn't exist. Aborting move"); 9923 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9924 } else if (!mp.srcArgs.getCodePath().equals( 9925 pkg.applicationInfo.sourceDir)) { 9926 Slog.w(TAG, "Package " + mp.packageName 9927 + " code path changed from " + mp.srcArgs.getCodePath() 9928 + " to " + pkg.applicationInfo.sourceDir 9929 + " Aborting move and returning error"); 9930 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9931 } else { 9932 final String oldCodePath = pkg.mPath; 9933 final String newCodePath = mp.targetArgs.getCodePath(); 9934 final String newResPath = mp.targetArgs.getResourcePath(); 9935 final String newNativePath = mp.targetArgs 9936 .getNativeLibraryPath(); 9937 9938 final File newNativeDir = new File(newNativePath); 9939 9940 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 9941 synchronized (mInstallLock) { 9942 if (mInstaller.linkNativeLibraryDirectory( 9943 pkg.applicationInfo.dataDir, newNativePath) < 0) { 9944 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9945 } 9946 } 9947 NativeLibraryHelper.copyNativeBinariesIfNeededLI(new File( 9948 newCodePath), newNativeDir); 9949 } else { 9950 synchronized (mInstallLock) { 9951 if (mInstaller.linkNativeLibraryDirectory( 9952 pkg.applicationInfo.dataDir, newNativePath) < 0) { 9953 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9954 } 9955 } 9956 } 9957 9958 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9959 pkg.mPath = newCodePath; 9960 // Move dex files around 9961 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 9962 // Moving of dex files failed. Set 9963 // error code and abort move. 9964 pkg.mPath = pkg.mScanPath; 9965 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9966 } 9967 } 9968 9969 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9970 pkg.mScanPath = newCodePath; 9971 pkg.applicationInfo.sourceDir = newCodePath; 9972 pkg.applicationInfo.publicSourceDir = newResPath; 9973 pkg.applicationInfo.nativeLibraryDir = newNativePath; 9974 PackageSetting ps = (PackageSetting) pkg.mExtras; 9975 ps.codePath = new File(pkg.applicationInfo.sourceDir); 9976 ps.codePathString = ps.codePath.getPath(); 9977 ps.resourcePath = new File( 9978 pkg.applicationInfo.publicSourceDir); 9979 ps.resourcePathString = ps.resourcePath.getPath(); 9980 ps.nativeLibraryPathString = newNativePath; 9981 // Set the application info flag 9982 // correctly. 9983 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 9984 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 9985 } else { 9986 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 9987 } 9988 ps.setFlags(pkg.applicationInfo.flags); 9989 mAppDirs.remove(oldCodePath); 9990 mAppDirs.put(newCodePath, pkg); 9991 // Persist settings 9992 mSettings.writeLPr(); 9993 } 9994 } 9995 } 9996 } 9997 // Send resources available broadcast 9998 sendResourcesChangedBroadcast(true, pkgList, uidArr, null); 9999 } 10000 } 10001 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 10002 // Clean up failed installation 10003 if (mp.targetArgs != null) { 10004 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 10005 -1); 10006 } 10007 } else { 10008 // Force a gc to clear things up. 10009 Runtime.getRuntime().gc(); 10010 // Delete older code 10011 synchronized (mInstallLock) { 10012 mp.srcArgs.doPostDeleteLI(true); 10013 } 10014 } 10015 10016 // Allow more operations on this file if we didn't fail because 10017 // an operation was already pending for this package. 10018 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 10019 synchronized (mPackages) { 10020 PackageParser.Package pkg = mPackages.get(mp.packageName); 10021 if (pkg != null) { 10022 pkg.mOperationPending = false; 10023 } 10024 } 10025 } 10026 10027 IPackageMoveObserver observer = mp.observer; 10028 if (observer != null) { 10029 try { 10030 observer.packageMoved(mp.packageName, returnCode); 10031 } catch (RemoteException e) { 10032 Log.i(TAG, "Observer no longer exists."); 10033 } 10034 } 10035 } 10036 }); 10037 } 10038 10039 public boolean setInstallLocation(int loc) { 10040 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 10041 null); 10042 if (getInstallLocation() == loc) { 10043 return true; 10044 } 10045 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 10046 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 10047 android.provider.Settings.System.putInt(mContext.getContentResolver(), 10048 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, loc); 10049 return true; 10050 } 10051 return false; 10052 } 10053 10054 public int getInstallLocation() { 10055 return android.provider.Settings.System.getInt(mContext.getContentResolver(), 10056 android.provider.Settings.Secure.DEFAULT_INSTALL_LOCATION, 10057 PackageHelper.APP_INSTALL_AUTO); 10058 } 10059 10060 /** Called by UserManagerService */ 10061 void cleanUpUserLILPw(int userHandle) { 10062 // Disable all the packages for the user first 10063 Set<Entry<String, PackageSetting>> entries = mSettings.mPackages.entrySet(); 10064 for (Entry<String, PackageSetting> entry : entries) { 10065 entry.getValue().removeUser(userHandle); 10066 } 10067 if (mDirtyUsers.remove(userHandle)); 10068 mSettings.removeUserLPr(userHandle); 10069 if (mInstaller != null) { 10070 // Technically, we shouldn't be doing this with the package lock 10071 // held. However, this is very rare, and there is already so much 10072 // other disk I/O going on, that we'll let it slide for now. 10073 mInstaller.removeUserDataDirs(userHandle); 10074 } 10075 } 10076 10077 /** Called by UserManagerService */ 10078 void createNewUserLILPw(int userHandle, File path) { 10079 if (mInstaller != null) { 10080 path.mkdir(); 10081 FileUtils.setPermissions(path.toString(), FileUtils.S_IRWXU | FileUtils.S_IRWXG 10082 | FileUtils.S_IXOTH, -1, -1); 10083 for (PackageSetting ps : mSettings.mPackages.values()) { 10084 // Only system apps are initially installed. 10085 ps.setInstalled((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) != 0, userHandle); 10086 // Need to create a data directory for all apps under this user. 10087 mInstaller.createUserData(ps.name, 10088 UserHandle.getUid(userHandle, ps.appId), userHandle); 10089 } 10090 mSettings.writePackageRestrictionsLPr(userHandle); 10091 } 10092 } 10093 10094 @Override 10095 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 10096 mContext.enforceCallingOrSelfPermission( 10097 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10098 "Only package verification agents can read the verifier device identity"); 10099 10100 synchronized (mPackages) { 10101 return mSettings.getVerifierDeviceIdentityLPw(); 10102 } 10103 } 10104 10105 @Override 10106 public void setPermissionEnforced(String permission, boolean enforced) { 10107 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 10108 if (READ_EXTERNAL_STORAGE.equals(permission)) { 10109 synchronized (mPackages) { 10110 if (mSettings.mReadExternalStorageEnforced == null 10111 || mSettings.mReadExternalStorageEnforced != enforced) { 10112 mSettings.mReadExternalStorageEnforced = enforced; 10113 mSettings.writeLPr(); 10114 10115 // kill any non-foreground processes so we restart them and 10116 // grant/revoke the GID. 10117 final IActivityManager am = ActivityManagerNative.getDefault(); 10118 if (am != null) { 10119 final long token = Binder.clearCallingIdentity(); 10120 try { 10121 am.killProcessesBelowForeground("setPermissionEnforcement"); 10122 } catch (RemoteException e) { 10123 } finally { 10124 Binder.restoreCallingIdentity(token); 10125 } 10126 } 10127 } 10128 } 10129 } else { 10130 throw new IllegalArgumentException("No selective enforcement for " + permission); 10131 } 10132 } 10133 10134 @Override 10135 public boolean isPermissionEnforced(String permission) { 10136 synchronized (mPackages) { 10137 return isPermissionEnforcedLocked(permission); 10138 } 10139 } 10140 10141 private boolean isPermissionEnforcedLocked(String permission) { 10142 if (READ_EXTERNAL_STORAGE.equals(permission)) { 10143 if (mSettings.mReadExternalStorageEnforced != null) { 10144 return mSettings.mReadExternalStorageEnforced; 10145 } else { 10146 // if user hasn't defined, fall back to secure default 10147 return Secure.getInt(mContext.getContentResolver(), 10148 Secure.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0) != 0; 10149 } 10150 } else { 10151 return true; 10152 } 10153 } 10154 10155 public boolean isStorageLow() { 10156 final long token = Binder.clearCallingIdentity(); 10157 try { 10158 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 10159 .getService(DeviceStorageMonitorService.SERVICE); 10160 return dsm.isMemoryLow(); 10161 } finally { 10162 Binder.restoreCallingIdentity(token); 10163 } 10164 } 10165} 10166