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