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