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