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