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