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