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