PackageManagerService.java revision cea3743499f4bb8e5f28a2e57686d7af313169c5
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 mAppDataDir = new File(dataDir, "data"); 1012 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 1013 mUserAppDataDir = new File(dataDir, "user"); 1014 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 1015 1016 sUserManager = new UserManagerService(context, this, 1017 mInstallLock, mPackages); 1018 1019 readPermissions(); 1020 1021 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 1022 long startTime = SystemClock.uptimeMillis(); 1023 1024 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 1025 startTime); 1026 1027 // Set flag to monitor and not change apk file paths when 1028 // scanning install directories. 1029 int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING; 1030 if (mNoDexOpt) { 1031 Slog.w(TAG, "Running ENG build: no pre-dexopt!"); 1032 scanMode |= SCAN_NO_DEX; 1033 } 1034 1035 final HashSet<String> libFiles = new HashSet<String>(); 1036 1037 mFrameworkDir = new File(Environment.getRootDirectory(), "framework"); 1038 mDalvikCacheDir = new File(dataDir, "dalvik-cache"); 1039 1040 boolean didDexOpt = false; 1041 1042 /** 1043 * Out of paranoia, ensure that everything in the boot class 1044 * path has been dexed. 1045 */ 1046 String bootClassPath = System.getProperty("java.boot.class.path"); 1047 if (bootClassPath != null) { 1048 String[] paths = splitString(bootClassPath, ':'); 1049 for (int i=0; i<paths.length; i++) { 1050 try { 1051 if (dalvik.system.DexFile.isDexOptNeeded(paths[i])) { 1052 libFiles.add(paths[i]); 1053 mInstaller.dexopt(paths[i], Process.SYSTEM_UID, true); 1054 didDexOpt = true; 1055 } 1056 } catch (FileNotFoundException e) { 1057 Slog.w(TAG, "Boot class path not found: " + paths[i]); 1058 } catch (IOException e) { 1059 Slog.w(TAG, "Cannot dexopt " + paths[i] + "; is it an APK or JAR? " 1060 + e.getMessage()); 1061 } 1062 } 1063 } else { 1064 Slog.w(TAG, "No BOOTCLASSPATH found!"); 1065 } 1066 1067 /** 1068 * Also ensure all external libraries have had dexopt run on them. 1069 */ 1070 if (mSharedLibraries.size() > 0) { 1071 Iterator<String> libs = mSharedLibraries.values().iterator(); 1072 while (libs.hasNext()) { 1073 String lib = libs.next(); 1074 try { 1075 if (dalvik.system.DexFile.isDexOptNeeded(lib)) { 1076 libFiles.add(lib); 1077 mInstaller.dexopt(lib, Process.SYSTEM_UID, true); 1078 didDexOpt = true; 1079 } 1080 } catch (FileNotFoundException e) { 1081 Slog.w(TAG, "Library not found: " + lib); 1082 } catch (IOException e) { 1083 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 1084 + e.getMessage()); 1085 } 1086 } 1087 } 1088 1089 // Gross hack for now: we know this file doesn't contain any 1090 // code, so don't dexopt it to avoid the resulting log spew. 1091 libFiles.add(mFrameworkDir.getPath() + "/framework-res.apk"); 1092 1093 /** 1094 * And there are a number of commands implemented in Java, which 1095 * we currently need to do the dexopt on so that they can be 1096 * run from a non-root shell. 1097 */ 1098 String[] frameworkFiles = mFrameworkDir.list(); 1099 if (frameworkFiles != null) { 1100 for (int i=0; i<frameworkFiles.length; i++) { 1101 File libPath = new File(mFrameworkDir, frameworkFiles[i]); 1102 String path = libPath.getPath(); 1103 // Skip the file if we alrady did it. 1104 if (libFiles.contains(path)) { 1105 continue; 1106 } 1107 // Skip the file if it is not a type we want to dexopt. 1108 if (!path.endsWith(".apk") && !path.endsWith(".jar")) { 1109 continue; 1110 } 1111 try { 1112 if (dalvik.system.DexFile.isDexOptNeeded(path)) { 1113 mInstaller.dexopt(path, Process.SYSTEM_UID, true); 1114 didDexOpt = true; 1115 } 1116 } catch (FileNotFoundException e) { 1117 Slog.w(TAG, "Jar not found: " + path); 1118 } catch (IOException e) { 1119 Slog.w(TAG, "Exception reading jar: " + path, e); 1120 } 1121 } 1122 } 1123 1124 if (didDexOpt) { 1125 // If we had to do a dexopt of one of the previous 1126 // things, then something on the system has changed. 1127 // Consider this significant, and wipe away all other 1128 // existing dexopt files to ensure we don't leave any 1129 // dangling around. 1130 String[] files = mDalvikCacheDir.list(); 1131 if (files != null) { 1132 for (int i=0; i<files.length; i++) { 1133 String fn = files[i]; 1134 if (fn.startsWith("data@app@") 1135 || fn.startsWith("data@app-private@")) { 1136 Slog.i(TAG, "Pruning dalvik file: " + fn); 1137 (new File(mDalvikCacheDir, fn)).delete(); 1138 } 1139 } 1140 } 1141 } 1142 1143 // Find base frameworks (resource packages without code). 1144 mFrameworkInstallObserver = new AppDirObserver( 1145 mFrameworkDir.getPath(), OBSERVER_EVENTS, true); 1146 mFrameworkInstallObserver.startWatching(); 1147 scanDirLI(mFrameworkDir, PackageParser.PARSE_IS_SYSTEM 1148 | PackageParser.PARSE_IS_SYSTEM_DIR, 1149 scanMode | SCAN_NO_DEX, 0); 1150 1151 // Collect all system packages. 1152 mSystemAppDir = new File(Environment.getRootDirectory(), "app"); 1153 mSystemInstallObserver = new AppDirObserver( 1154 mSystemAppDir.getPath(), OBSERVER_EVENTS, true); 1155 mSystemInstallObserver.startWatching(); 1156 scanDirLI(mSystemAppDir, PackageParser.PARSE_IS_SYSTEM 1157 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1158 1159 // Collect all vendor packages. 1160 mVendorAppDir = new File("/vendor/app"); 1161 mVendorInstallObserver = new AppDirObserver( 1162 mVendorAppDir.getPath(), OBSERVER_EVENTS, true); 1163 mVendorInstallObserver.startWatching(); 1164 scanDirLI(mVendorAppDir, PackageParser.PARSE_IS_SYSTEM 1165 | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0); 1166 1167 if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands"); 1168 mInstaller.moveFiles(); 1169 1170 // Prune any system packages that no longer exist. 1171 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 1172 if (!mOnlyCore) { 1173 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 1174 while (psit.hasNext()) { 1175 PackageSetting ps = psit.next(); 1176 1177 /* 1178 * If this is not a system app, it can't be a 1179 * disable system app. 1180 */ 1181 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 1182 continue; 1183 } 1184 1185 /* 1186 * If the package is scanned, it's not erased. 1187 */ 1188 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 1189 if (scannedPkg != null) { 1190 /* 1191 * If the system app is both scanned and in the 1192 * disabled packages list, then it must have been 1193 * added via OTA. Remove it from the currently 1194 * scanned package so the previously user-installed 1195 * application can be scanned. 1196 */ 1197 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 1198 Slog.i(TAG, "Expecting better updatd system app for " + ps.name 1199 + "; removing system app"); 1200 removePackageLI(ps, true); 1201 } 1202 1203 continue; 1204 } 1205 1206 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 1207 psit.remove(); 1208 String msg = "System package " + ps.name 1209 + " no longer exists; wiping its data"; 1210 reportSettingsProblem(Log.WARN, msg); 1211 removeDataDirsLI(ps.name); 1212 } else { 1213 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 1214 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 1215 possiblyDeletedUpdatedSystemApps.add(ps.name); 1216 } 1217 } 1218 } 1219 } 1220 1221 mAppInstallDir = new File(dataDir, "app"); 1222 mAppLibInstallDir = new File(dataDir, "app-lib"); 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 null; 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 null; 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 null; 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 null; 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 createDataDirsLI(String packageName, int uid) { 3580 int[] users = sUserManager.getUserIds(); 3581 int res = mInstaller.install(packageName, uid, uid); 3582 if (res < 0) { 3583 return res; 3584 } 3585 for (int user : users) { 3586 if (user != 0) { 3587 res = mInstaller.createUserData(packageName, 3588 UserHandle.getUid(user, uid), user); 3589 if (res < 0) { 3590 return res; 3591 } 3592 } 3593 } 3594 return res; 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, 0); 3934 3935 boolean uidError = false; 3936 3937 if (dataPath.exists()) { 3938 int currentUid = 0; 3939 try { 3940 StructStat stat = Libcore.os.stat(dataPath.getPath()); 3941 currentUid = stat.st_uid; 3942 } catch (ErrnoException e) { 3943 Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e); 3944 } 3945 3946 // If we have mismatched owners for the data path, we have a problem. 3947 if (currentUid != pkg.applicationInfo.uid) { 3948 boolean recovered = false; 3949 if (currentUid == 0) { 3950 // The directory somehow became owned by root. Wow. 3951 // This is probably because the system was stopped while 3952 // installd was in the middle of messing with its libs 3953 // directory. Ask installd to fix that. 3954 int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid, 3955 pkg.applicationInfo.uid); 3956 if (ret >= 0) { 3957 recovered = true; 3958 String msg = "Package " + pkg.packageName 3959 + " unexpectedly changed to uid 0; recovered to " + 3960 + pkg.applicationInfo.uid; 3961 reportSettingsProblem(Log.WARN, msg); 3962 } 3963 } 3964 if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 3965 || (scanMode&SCAN_BOOTING) != 0)) { 3966 // If this is a system app, we can at least delete its 3967 // current data so the application will still work. 3968 int ret = removeDataDirsLI(pkgName); 3969 if (ret >= 0) { 3970 // TODO: Kill the processes first 3971 // Old data gone! 3972 String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0 3973 ? "System package " : "Third party package "; 3974 String msg = prefix + pkg.packageName 3975 + " has changed from uid: " 3976 + currentUid + " to " 3977 + pkg.applicationInfo.uid + "; old data erased"; 3978 reportSettingsProblem(Log.WARN, msg); 3979 recovered = true; 3980 3981 // And now re-install the app. 3982 ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid); 3983 if (ret == -1) { 3984 // Ack should not happen! 3985 msg = prefix + pkg.packageName 3986 + " could not have data directory re-created after delete."; 3987 reportSettingsProblem(Log.WARN, msg); 3988 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 3989 return null; 3990 } 3991 } 3992 if (!recovered) { 3993 mHasSystemUidErrors = true; 3994 } 3995 } else if (!recovered) { 3996 // If we allow this install to proceed, we will be broken. 3997 // Abort, abort! 3998 mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED; 3999 return null; 4000 } 4001 if (!recovered) { 4002 pkg.applicationInfo.dataDir = "/mismatched_uid/settings_" 4003 + pkg.applicationInfo.uid + "/fs_" 4004 + currentUid; 4005 pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir; 4006 String msg = "Package " + pkg.packageName 4007 + " has mismatched uid: " 4008 + currentUid + " on disk, " 4009 + pkg.applicationInfo.uid + " in settings"; 4010 // writer 4011 synchronized (mPackages) { 4012 mSettings.mReadMessages.append(msg); 4013 mSettings.mReadMessages.append('\n'); 4014 uidError = true; 4015 if (!pkgSetting.uidError) { 4016 reportSettingsProblem(Log.ERROR, msg); 4017 } 4018 } 4019 } 4020 } 4021 pkg.applicationInfo.dataDir = dataPath.getPath(); 4022 } else { 4023 if (DEBUG_PACKAGE_SCANNING) { 4024 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4025 Log.v(TAG, "Want this data dir: " + dataPath); 4026 } 4027 //invoke installer to do the actual installation 4028 int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid); 4029 if (ret < 0) { 4030 // Error from installer 4031 mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 4032 return null; 4033 } 4034 4035 if (dataPath.exists()) { 4036 pkg.applicationInfo.dataDir = dataPath.getPath(); 4037 } else { 4038 Slog.w(TAG, "Unable to create data directory: " + dataPath); 4039 pkg.applicationInfo.dataDir = null; 4040 } 4041 } 4042 4043 /* 4044 * Set the data dir to the default "/data/data/<package name>/lib" 4045 * if we got here without anyone telling us different (e.g., apps 4046 * stored on SD card have their native libraries stored in the ASEC 4047 * container with the APK). 4048 * 4049 * This happens during an upgrade from a package settings file that 4050 * doesn't have a native library path attribute at all. 4051 */ 4052 if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) { 4053 if (pkgSetting.nativeLibraryPathString == null) { 4054 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4055 } else { 4056 pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString; 4057 } 4058 } 4059 4060 pkgSetting.uidError = uidError; 4061 } 4062 4063 String path = scanFile.getPath(); 4064 /* Note: We don't want to unpack the native binaries for 4065 * system applications, unless they have been updated 4066 * (the binaries are already under /system/lib). 4067 * Also, don't unpack libs for apps on the external card 4068 * since they should have their libraries in the ASEC 4069 * container already. 4070 * 4071 * In other words, we're going to unpack the binaries 4072 * only for non-system apps and system app upgrades. 4073 */ 4074 if (pkg.applicationInfo.nativeLibraryDir != null) { 4075 try { 4076 File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 4077 final String dataPathString = dataPath.getCanonicalPath(); 4078 4079 if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) { 4080 /* 4081 * Upgrading from a previous version of the OS sometimes 4082 * leaves native libraries in the /data/data/<app>/lib 4083 * directory for system apps even when they shouldn't be. 4084 * Recent changes in the JNI library search path 4085 * necessitates we remove those to match previous behavior. 4086 */ 4087 if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) { 4088 Log.i(TAG, "removed obsolete native libraries for system package " 4089 + path); 4090 } 4091 } else { 4092 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 4093 /* 4094 * Update native library dir if it starts with 4095 * /data/data 4096 */ 4097 if (nativeLibraryDir.getPath().startsWith(dataPathString)) { 4098 setInternalAppNativeLibraryPath(pkg, pkgSetting); 4099 nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir); 4100 } 4101 4102 try { 4103 if (copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir) != PackageManager.INSTALL_SUCCEEDED) { 4104 Slog.e(TAG, "Unable to copy native libraries"); 4105 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4106 return null; 4107 } 4108 } catch (IOException e) { 4109 Slog.e(TAG, "Unable to copy native libraries", e); 4110 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4111 return null; 4112 } 4113 } 4114 4115 Slog.i(TAG, "Linking native library dir for " + path); 4116 final int[] userIds = sUserManager.getUserIds(); 4117 synchronized (mInstallLock) { 4118 for (int userId : userIds) { 4119 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 4120 pkg.applicationInfo.nativeLibraryDir, userId) < 0) { 4121 Slog.w(TAG, "Failed linking native library dir (user=" + userId 4122 + ")"); 4123 mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 4124 return null; 4125 } 4126 } 4127 } 4128 } 4129 } catch (IOException ioe) { 4130 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 4131 } 4132 } 4133 pkg.mScanPath = path; 4134 4135 if ((scanMode&SCAN_NO_DEX) == 0) { 4136 if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0) 4137 == DEX_OPT_FAILED) { 4138 mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT; 4139 return null; 4140 } 4141 } 4142 4143 if (mFactoryTest && pkg.requestedPermissions.contains( 4144 android.Manifest.permission.FACTORY_TEST)) { 4145 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 4146 } 4147 4148 // Request the ActivityManager to kill the process(only for existing packages) 4149 // so that we do not end up in a confused state while the user is still using the older 4150 // version of the application while the new one gets installed. 4151 if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 4152 killApplication(pkg.applicationInfo.packageName, 4153 pkg.applicationInfo.uid); 4154 } 4155 4156 // writer 4157 synchronized (mPackages) { 4158 // We don't expect installation to fail beyond this point, 4159 if ((scanMode&SCAN_MONITOR) != 0) { 4160 mAppDirs.put(pkg.mPath, pkg); 4161 } 4162 // Add the new setting to mSettings 4163 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 4164 // Add the new setting to mPackages 4165 mPackages.put(pkg.applicationInfo.packageName, pkg); 4166 // Make sure we don't accidentally delete its data. 4167 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 4168 while (iter.hasNext()) { 4169 PackageCleanItem item = iter.next(); 4170 if (pkgName.equals(item.packageName)) { 4171 iter.remove(); 4172 } 4173 } 4174 4175 // Take care of first install / last update times. 4176 if (currentTime != 0) { 4177 if (pkgSetting.firstInstallTime == 0) { 4178 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 4179 } else if ((scanMode&SCAN_UPDATE_TIME) != 0) { 4180 pkgSetting.lastUpdateTime = currentTime; 4181 } 4182 } else if (pkgSetting.firstInstallTime == 0) { 4183 // We need *something*. Take time time stamp of the file. 4184 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 4185 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 4186 if (scanFileTime != pkgSetting.timeStamp) { 4187 // A package on the system image has changed; consider this 4188 // to be an update. 4189 pkgSetting.lastUpdateTime = scanFileTime; 4190 } 4191 } 4192 4193 int N = pkg.providers.size(); 4194 StringBuilder r = null; 4195 int i; 4196 for (i=0; i<N; i++) { 4197 PackageParser.Provider p = pkg.providers.get(i); 4198 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 4199 p.info.processName, pkg.applicationInfo.uid); 4200 mProvidersByComponent.put(new ComponentName(p.info.packageName, 4201 p.info.name), p); 4202 p.syncable = p.info.isSyncable; 4203 if (p.info.authority != null) { 4204 String names[] = p.info.authority.split(";"); 4205 p.info.authority = null; 4206 for (int j = 0; j < names.length; j++) { 4207 if (j == 1 && p.syncable) { 4208 // We only want the first authority for a provider to possibly be 4209 // syncable, so if we already added this provider using a different 4210 // authority clear the syncable flag. We copy the provider before 4211 // changing it because the mProviders object contains a reference 4212 // to a provider that we don't want to change. 4213 // Only do this for the second authority since the resulting provider 4214 // object can be the same for all future authorities for this provider. 4215 p = new PackageParser.Provider(p); 4216 p.syncable = false; 4217 } 4218 if (!mProviders.containsKey(names[j])) { 4219 mProviders.put(names[j], p); 4220 if (p.info.authority == null) { 4221 p.info.authority = names[j]; 4222 } else { 4223 p.info.authority = p.info.authority + ";" + names[j]; 4224 } 4225 if (DEBUG_PACKAGE_SCANNING) { 4226 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 4227 Log.d(TAG, "Registered content provider: " + names[j] 4228 + ", className = " + p.info.name + ", isSyncable = " 4229 + p.info.isSyncable); 4230 } 4231 } else { 4232 PackageParser.Provider other = mProviders.get(names[j]); 4233 Slog.w(TAG, "Skipping provider name " + names[j] + 4234 " (in package " + pkg.applicationInfo.packageName + 4235 "): name already used by " 4236 + ((other != null && other.getComponentName() != null) 4237 ? other.getComponentName().getPackageName() : "?")); 4238 } 4239 } 4240 } 4241 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4242 if (r == null) { 4243 r = new StringBuilder(256); 4244 } else { 4245 r.append(' '); 4246 } 4247 r.append(p.info.name); 4248 } 4249 } 4250 if (r != null) { 4251 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 4252 } 4253 4254 N = pkg.services.size(); 4255 r = null; 4256 for (i=0; i<N; i++) { 4257 PackageParser.Service s = pkg.services.get(i); 4258 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 4259 s.info.processName, pkg.applicationInfo.uid); 4260 mServices.addService(s); 4261 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4262 if (r == null) { 4263 r = new StringBuilder(256); 4264 } else { 4265 r.append(' '); 4266 } 4267 r.append(s.info.name); 4268 } 4269 } 4270 if (r != null) { 4271 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 4272 } 4273 4274 N = pkg.receivers.size(); 4275 r = null; 4276 for (i=0; i<N; i++) { 4277 PackageParser.Activity a = pkg.receivers.get(i); 4278 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4279 a.info.processName, pkg.applicationInfo.uid); 4280 mReceivers.addActivity(a, "receiver"); 4281 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4282 if (r == null) { 4283 r = new StringBuilder(256); 4284 } else { 4285 r.append(' '); 4286 } 4287 r.append(a.info.name); 4288 } 4289 } 4290 if (r != null) { 4291 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 4292 } 4293 4294 N = pkg.activities.size(); 4295 r = null; 4296 for (i=0; i<N; i++) { 4297 PackageParser.Activity a = pkg.activities.get(i); 4298 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 4299 a.info.processName, pkg.applicationInfo.uid); 4300 mActivities.addActivity(a, "activity"); 4301 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4302 if (r == null) { 4303 r = new StringBuilder(256); 4304 } else { 4305 r.append(' '); 4306 } 4307 r.append(a.info.name); 4308 } 4309 } 4310 if (r != null) { 4311 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 4312 } 4313 4314 N = pkg.permissionGroups.size(); 4315 r = null; 4316 for (i=0; i<N; i++) { 4317 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 4318 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 4319 if (cur == null) { 4320 mPermissionGroups.put(pg.info.name, pg); 4321 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4322 if (r == null) { 4323 r = new StringBuilder(256); 4324 } else { 4325 r.append(' '); 4326 } 4327 r.append(pg.info.name); 4328 } 4329 } else { 4330 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 4331 + pg.info.packageName + " ignored: original from " 4332 + cur.info.packageName); 4333 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4334 if (r == null) { 4335 r = new StringBuilder(256); 4336 } else { 4337 r.append(' '); 4338 } 4339 r.append("DUP:"); 4340 r.append(pg.info.name); 4341 } 4342 } 4343 } 4344 if (r != null) { 4345 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 4346 } 4347 4348 N = pkg.permissions.size(); 4349 r = null; 4350 for (i=0; i<N; i++) { 4351 PackageParser.Permission p = pkg.permissions.get(i); 4352 HashMap<String, BasePermission> permissionMap = 4353 p.tree ? mSettings.mPermissionTrees 4354 : mSettings.mPermissions; 4355 p.group = mPermissionGroups.get(p.info.group); 4356 if (p.info.group == null || p.group != null) { 4357 BasePermission bp = permissionMap.get(p.info.name); 4358 if (bp == null) { 4359 bp = new BasePermission(p.info.name, p.info.packageName, 4360 BasePermission.TYPE_NORMAL); 4361 permissionMap.put(p.info.name, bp); 4362 } 4363 if (bp.perm == null) { 4364 if (bp.sourcePackage == null 4365 || bp.sourcePackage.equals(p.info.packageName)) { 4366 BasePermission tree = findPermissionTreeLP(p.info.name); 4367 if (tree == null 4368 || tree.sourcePackage.equals(p.info.packageName)) { 4369 bp.packageSetting = pkgSetting; 4370 bp.perm = p; 4371 bp.uid = pkg.applicationInfo.uid; 4372 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4373 if (r == null) { 4374 r = new StringBuilder(256); 4375 } else { 4376 r.append(' '); 4377 } 4378 r.append(p.info.name); 4379 } 4380 } else { 4381 Slog.w(TAG, "Permission " + p.info.name + " from package " 4382 + p.info.packageName + " ignored: base tree " 4383 + tree.name + " is from package " 4384 + tree.sourcePackage); 4385 } 4386 } else { 4387 Slog.w(TAG, "Permission " + p.info.name + " from package " 4388 + p.info.packageName + " ignored: original from " 4389 + bp.sourcePackage); 4390 } 4391 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4392 if (r == null) { 4393 r = new StringBuilder(256); 4394 } else { 4395 r.append(' '); 4396 } 4397 r.append("DUP:"); 4398 r.append(p.info.name); 4399 } 4400 if (bp.perm == p) { 4401 bp.protectionLevel = p.info.protectionLevel; 4402 } 4403 } else { 4404 Slog.w(TAG, "Permission " + p.info.name + " from package " 4405 + p.info.packageName + " ignored: no group " 4406 + p.group); 4407 } 4408 } 4409 if (r != null) { 4410 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 4411 } 4412 4413 N = pkg.instrumentation.size(); 4414 r = null; 4415 for (i=0; i<N; i++) { 4416 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 4417 a.info.packageName = pkg.applicationInfo.packageName; 4418 a.info.sourceDir = pkg.applicationInfo.sourceDir; 4419 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 4420 a.info.dataDir = pkg.applicationInfo.dataDir; 4421 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 4422 mInstrumentation.put(a.getComponentName(), a); 4423 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 4424 if (r == null) { 4425 r = new StringBuilder(256); 4426 } else { 4427 r.append(' '); 4428 } 4429 r.append(a.info.name); 4430 } 4431 } 4432 if (r != null) { 4433 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 4434 } 4435 4436 if (pkg.protectedBroadcasts != null) { 4437 N = pkg.protectedBroadcasts.size(); 4438 for (i=0; i<N; i++) { 4439 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 4440 } 4441 } 4442 4443 pkgSetting.setTimeStamp(scanFileTime); 4444 } 4445 4446 return pkg; 4447 } 4448 4449 private void setInternalAppNativeLibraryPath(PackageParser.Package pkg, 4450 PackageSetting pkgSetting) { 4451 final String apkLibPath = getApkName(pkgSetting.codePathString); 4452 final String nativeLibraryPath = new File(mAppLibInstallDir, apkLibPath).getPath(); 4453 pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath; 4454 pkgSetting.nativeLibraryPathString = nativeLibraryPath; 4455 } 4456 4457 private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir) 4458 throws IOException { 4459 if (!nativeLibraryDir.isDirectory()) { 4460 nativeLibraryDir.delete(); 4461 4462 if (!nativeLibraryDir.mkdir()) { 4463 throw new IOException("Cannot create " + nativeLibraryDir.getPath()); 4464 } 4465 4466 try { 4467 Libcore.os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH 4468 | S_IXOTH); 4469 } catch (ErrnoException e) { 4470 throw new IOException("Cannot chmod native library directory " 4471 + nativeLibraryDir.getPath(), e); 4472 } 4473 } else if (!SELinux.restorecon(nativeLibraryDir)) { 4474 throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath()); 4475 } 4476 4477 /* 4478 * If this is an internal application or our nativeLibraryPath points to 4479 * the app-lib directory, unpack the libraries if necessary. 4480 */ 4481 return NativeLibraryHelper.copyNativeBinariesIfNeededLI(scanFile, nativeLibraryDir); 4482 } 4483 4484 private void killApplication(String pkgName, int appId) { 4485 // Request the ActivityManager to kill the process(only for existing packages) 4486 // so that we do not end up in a confused state while the user is still using the older 4487 // version of the application while the new one gets installed. 4488 IActivityManager am = ActivityManagerNative.getDefault(); 4489 if (am != null) { 4490 try { 4491 am.killApplicationWithAppId(pkgName, appId); 4492 } catch (RemoteException e) { 4493 } 4494 } 4495 } 4496 4497 void removePackageLI(PackageSetting ps, boolean chatty) { 4498 if (DEBUG_INSTALL) { 4499 if (chatty) 4500 Log.d(TAG, "Removing package " + ps.name); 4501 } 4502 4503 // writer 4504 synchronized (mPackages) { 4505 mPackages.remove(ps.name); 4506 if (ps.codePathString != null) { 4507 mAppDirs.remove(ps.codePathString); 4508 } 4509 4510 final PackageParser.Package pkg = ps.pkg; 4511 if (pkg != null) { 4512 cleanPackageDataStructuresLILPw(pkg, chatty); 4513 } 4514 } 4515 } 4516 4517 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 4518 if (DEBUG_INSTALL) { 4519 if (chatty) 4520 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 4521 } 4522 4523 // writer 4524 synchronized (mPackages) { 4525 mPackages.remove(pkg.applicationInfo.packageName); 4526 if (pkg.mPath != null) { 4527 mAppDirs.remove(pkg.mPath); 4528 } 4529 cleanPackageDataStructuresLILPw(pkg, chatty); 4530 } 4531 } 4532 4533 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 4534 int N = pkg.providers.size(); 4535 StringBuilder r = null; 4536 int i; 4537 for (i=0; i<N; i++) { 4538 PackageParser.Provider p = pkg.providers.get(i); 4539 mProvidersByComponent.remove(new ComponentName(p.info.packageName, 4540 p.info.name)); 4541 if (p.info.authority == null) { 4542 4543 /* There was another ContentProvider with this authority when 4544 * this app was installed so this authority is null, 4545 * Ignore it as we don't have to unregister the provider. 4546 */ 4547 continue; 4548 } 4549 String names[] = p.info.authority.split(";"); 4550 for (int j = 0; j < names.length; j++) { 4551 if (mProviders.get(names[j]) == p) { 4552 mProviders.remove(names[j]); 4553 if (DEBUG_REMOVE) { 4554 if (chatty) 4555 Log.d(TAG, "Unregistered content provider: " + names[j] 4556 + ", className = " + p.info.name + ", isSyncable = " 4557 + p.info.isSyncable); 4558 } 4559 } 4560 } 4561 if (chatty) { 4562 if (r == null) { 4563 r = new StringBuilder(256); 4564 } else { 4565 r.append(' '); 4566 } 4567 r.append(p.info.name); 4568 } 4569 } 4570 if (r != null) { 4571 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 4572 } 4573 4574 N = pkg.services.size(); 4575 r = null; 4576 for (i=0; i<N; i++) { 4577 PackageParser.Service s = pkg.services.get(i); 4578 mServices.removeService(s); 4579 if (chatty) { 4580 if (r == null) { 4581 r = new StringBuilder(256); 4582 } else { 4583 r.append(' '); 4584 } 4585 r.append(s.info.name); 4586 } 4587 } 4588 if (r != null) { 4589 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 4590 } 4591 4592 N = pkg.receivers.size(); 4593 r = null; 4594 for (i=0; i<N; i++) { 4595 PackageParser.Activity a = pkg.receivers.get(i); 4596 mReceivers.removeActivity(a, "receiver"); 4597 if (chatty) { 4598 if (r == null) { 4599 r = new StringBuilder(256); 4600 } else { 4601 r.append(' '); 4602 } 4603 r.append(a.info.name); 4604 } 4605 } 4606 if (r != null) { 4607 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 4608 } 4609 4610 N = pkg.activities.size(); 4611 r = null; 4612 for (i=0; i<N; i++) { 4613 PackageParser.Activity a = pkg.activities.get(i); 4614 mActivities.removeActivity(a, "activity"); 4615 if (chatty) { 4616 if (r == null) { 4617 r = new StringBuilder(256); 4618 } else { 4619 r.append(' '); 4620 } 4621 r.append(a.info.name); 4622 } 4623 } 4624 if (r != null) { 4625 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 4626 } 4627 4628 N = pkg.permissions.size(); 4629 r = null; 4630 for (i=0; i<N; i++) { 4631 PackageParser.Permission p = pkg.permissions.get(i); 4632 BasePermission bp = mSettings.mPermissions.get(p.info.name); 4633 if (bp == null) { 4634 bp = mSettings.mPermissionTrees.get(p.info.name); 4635 } 4636 if (bp != null && bp.perm == p) { 4637 bp.perm = null; 4638 if (chatty) { 4639 if (r == null) { 4640 r = new StringBuilder(256); 4641 } else { 4642 r.append(' '); 4643 } 4644 r.append(p.info.name); 4645 } 4646 } 4647 } 4648 if (r != null) { 4649 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 4650 } 4651 4652 N = pkg.instrumentation.size(); 4653 r = null; 4654 for (i=0; i<N; i++) { 4655 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 4656 mInstrumentation.remove(a.getComponentName()); 4657 if (chatty) { 4658 if (r == null) { 4659 r = new StringBuilder(256); 4660 } else { 4661 r.append(' '); 4662 } 4663 r.append(a.info.name); 4664 } 4665 } 4666 if (r != null) { 4667 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 4668 } 4669 } 4670 4671 private static final boolean isPackageFilename(String name) { 4672 return name != null && name.endsWith(".apk"); 4673 } 4674 4675 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 4676 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 4677 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 4678 return true; 4679 } 4680 } 4681 return false; 4682 } 4683 4684 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 4685 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 4686 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 4687 4688 private void updatePermissionsLPw(String changingPkg, 4689 PackageParser.Package pkgInfo, int flags) { 4690 // Make sure there are no dangling permission trees. 4691 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 4692 while (it.hasNext()) { 4693 final BasePermission bp = it.next(); 4694 if (bp.packageSetting == null) { 4695 // We may not yet have parsed the package, so just see if 4696 // we still know about its settings. 4697 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 4698 } 4699 if (bp.packageSetting == null) { 4700 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 4701 + " from package " + bp.sourcePackage); 4702 it.remove(); 4703 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 4704 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 4705 Slog.i(TAG, "Removing old permission tree: " + bp.name 4706 + " from package " + bp.sourcePackage); 4707 flags |= UPDATE_PERMISSIONS_ALL; 4708 it.remove(); 4709 } 4710 } 4711 } 4712 4713 // Make sure all dynamic permissions have been assigned to a package, 4714 // and make sure there are no dangling permissions. 4715 it = mSettings.mPermissions.values().iterator(); 4716 while (it.hasNext()) { 4717 final BasePermission bp = it.next(); 4718 if (bp.type == BasePermission.TYPE_DYNAMIC) { 4719 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 4720 + bp.name + " pkg=" + bp.sourcePackage 4721 + " info=" + bp.pendingInfo); 4722 if (bp.packageSetting == null && bp.pendingInfo != null) { 4723 final BasePermission tree = findPermissionTreeLP(bp.name); 4724 if (tree != null && tree.perm != null) { 4725 bp.packageSetting = tree.packageSetting; 4726 bp.perm = new PackageParser.Permission(tree.perm.owner, 4727 new PermissionInfo(bp.pendingInfo)); 4728 bp.perm.info.packageName = tree.perm.info.packageName; 4729 bp.perm.info.name = bp.name; 4730 bp.uid = tree.uid; 4731 } 4732 } 4733 } 4734 if (bp.packageSetting == null) { 4735 // We may not yet have parsed the package, so just see if 4736 // we still know about its settings. 4737 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 4738 } 4739 if (bp.packageSetting == null) { 4740 Slog.w(TAG, "Removing dangling permission: " + bp.name 4741 + " from package " + bp.sourcePackage); 4742 it.remove(); 4743 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 4744 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 4745 Slog.i(TAG, "Removing old permission: " + bp.name 4746 + " from package " + bp.sourcePackage); 4747 flags |= UPDATE_PERMISSIONS_ALL; 4748 it.remove(); 4749 } 4750 } 4751 } 4752 4753 // Now update the permissions for all packages, in particular 4754 // replace the granted permissions of the system packages. 4755 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 4756 for (PackageParser.Package pkg : mPackages.values()) { 4757 if (pkg != pkgInfo) { 4758 grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0); 4759 } 4760 } 4761 } 4762 4763 if (pkgInfo != null) { 4764 grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0); 4765 } 4766 } 4767 4768 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) { 4769 final PackageSetting ps = (PackageSetting) pkg.mExtras; 4770 if (ps == null) { 4771 return; 4772 } 4773 final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps; 4774 HashSet<String> origPermissions = gp.grantedPermissions; 4775 boolean changedPermission = false; 4776 4777 if (replace) { 4778 ps.permissionsFixed = false; 4779 if (gp == ps) { 4780 origPermissions = new HashSet<String>(gp.grantedPermissions); 4781 gp.grantedPermissions.clear(); 4782 gp.gids = mGlobalGids; 4783 } 4784 } 4785 4786 if (gp.gids == null) { 4787 gp.gids = mGlobalGids; 4788 } 4789 4790 final int N = pkg.requestedPermissions.size(); 4791 for (int i=0; i<N; i++) { 4792 final String name = pkg.requestedPermissions.get(i); 4793 //final boolean required = pkg.requestedPermssionsRequired.get(i); 4794 final BasePermission bp = mSettings.mPermissions.get(name); 4795 if (DEBUG_INSTALL) { 4796 if (gp != ps) { 4797 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 4798 } 4799 } 4800 if (bp != null && bp.packageSetting != null) { 4801 final String perm = bp.name; 4802 boolean allowed; 4803 boolean allowedSig = false; 4804 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 4805 if (level == PermissionInfo.PROTECTION_NORMAL 4806 || level == PermissionInfo.PROTECTION_DANGEROUS) { 4807 allowed = true; 4808 } else if (bp.packageSetting == null) { 4809 // This permission is invalid; skip it. 4810 allowed = false; 4811 } else if (level == PermissionInfo.PROTECTION_SIGNATURE) { 4812 allowed = (compareSignatures( 4813 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 4814 == PackageManager.SIGNATURE_MATCH) 4815 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 4816 == PackageManager.SIGNATURE_MATCH); 4817 if (!allowed && (bp.protectionLevel 4818 & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) { 4819 if (isSystemApp(pkg)) { 4820 // For updated system applications, a system permission 4821 // is granted only if it had been defined by the original application. 4822 if (isUpdatedSystemApp(pkg)) { 4823 final PackageSetting sysPs = mSettings 4824 .getDisabledSystemPkgLPr(pkg.packageName); 4825 final GrantedPermissions origGp = sysPs.sharedUser != null 4826 ? sysPs.sharedUser : sysPs; 4827 if (origGp.grantedPermissions.contains(perm)) { 4828 allowed = true; 4829 } else { 4830 allowed = false; 4831 } 4832 } else { 4833 allowed = true; 4834 } 4835 } 4836 } 4837 if (!allowed && (bp.protectionLevel 4838 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 4839 // For development permissions, a development permission 4840 // is granted only if it was already granted. 4841 if (origPermissions.contains(perm)) { 4842 allowed = true; 4843 } else { 4844 allowed = false; 4845 } 4846 } 4847 if (allowed) { 4848 allowedSig = true; 4849 } 4850 } else { 4851 allowed = false; 4852 } 4853 if (DEBUG_INSTALL) { 4854 if (gp != ps) { 4855 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 4856 } 4857 } 4858 if (allowed) { 4859 if ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 4860 && ps.permissionsFixed) { 4861 // If this is an existing, non-system package, then 4862 // we can't add any new permissions to it. 4863 if (!allowedSig && !gp.grantedPermissions.contains(perm)) { 4864 allowed = false; 4865 // Except... if this is a permission that was added 4866 // to the platform (note: need to only do this when 4867 // updating the platform). 4868 final int NP = PackageParser.NEW_PERMISSIONS.length; 4869 for (int ip=0; ip<NP; ip++) { 4870 final PackageParser.NewPermissionInfo npi 4871 = PackageParser.NEW_PERMISSIONS[ip]; 4872 if (npi.name.equals(perm) 4873 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 4874 allowed = true; 4875 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 4876 + pkg.packageName); 4877 break; 4878 } 4879 } 4880 } 4881 } 4882 if (allowed) { 4883 if (!gp.grantedPermissions.contains(perm)) { 4884 changedPermission = true; 4885 gp.grantedPermissions.add(perm); 4886 gp.gids = appendInts(gp.gids, bp.gids); 4887 } else if (!ps.haveGids) { 4888 gp.gids = appendInts(gp.gids, bp.gids); 4889 } 4890 } else { 4891 Slog.w(TAG, "Not granting permission " + perm 4892 + " to package " + pkg.packageName 4893 + " because it was previously installed without"); 4894 } 4895 } else { 4896 if (gp.grantedPermissions.remove(perm)) { 4897 changedPermission = true; 4898 gp.gids = removeInts(gp.gids, bp.gids); 4899 Slog.i(TAG, "Un-granting permission " + perm 4900 + " from package " + pkg.packageName 4901 + " (protectionLevel=" + bp.protectionLevel 4902 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 4903 + ")"); 4904 } else { 4905 Slog.w(TAG, "Not granting permission " + perm 4906 + " to package " + pkg.packageName 4907 + " (protectionLevel=" + bp.protectionLevel 4908 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 4909 + ")"); 4910 } 4911 } 4912 } else { 4913 Slog.w(TAG, "Unknown permission " + name 4914 + " in package " + pkg.packageName); 4915 } 4916 } 4917 4918 if ((changedPermission || replace) && !ps.permissionsFixed && 4919 ((ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) || 4920 ((ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0)){ 4921 // This is the first that we have heard about this package, so the 4922 // permissions we have now selected are fixed until explicitly 4923 // changed. 4924 ps.permissionsFixed = true; 4925 } 4926 ps.haveGids = true; 4927 } 4928 4929 private final class ActivityIntentResolver 4930 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 4931 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 4932 boolean defaultOnly, int userId) { 4933 if (!sUserManager.exists(userId)) return null; 4934 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 4935 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 4936 } 4937 4938 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 4939 int userId) { 4940 if (!sUserManager.exists(userId)) return null; 4941 mFlags = flags; 4942 return super.queryIntent(intent, resolvedType, 4943 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 4944 } 4945 4946 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 4947 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 4948 if (!sUserManager.exists(userId)) return null; 4949 if (packageActivities == null) { 4950 return null; 4951 } 4952 mFlags = flags; 4953 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 4954 final int N = packageActivities.size(); 4955 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 4956 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 4957 4958 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 4959 for (int i = 0; i < N; ++i) { 4960 intentFilters = packageActivities.get(i).intents; 4961 if (intentFilters != null && intentFilters.size() > 0) { 4962 PackageParser.ActivityIntentInfo[] array = 4963 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 4964 intentFilters.toArray(array); 4965 listCut.add(array); 4966 } 4967 } 4968 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 4969 } 4970 4971 public final void addActivity(PackageParser.Activity a, String type) { 4972 final boolean systemApp = isSystemApp(a.info.applicationInfo); 4973 mActivities.put(a.getComponentName(), a); 4974 if (DEBUG_SHOW_INFO) 4975 Log.v( 4976 TAG, " " + type + " " + 4977 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 4978 if (DEBUG_SHOW_INFO) 4979 Log.v(TAG, " Class=" + a.info.name); 4980 final int NI = a.intents.size(); 4981 for (int j=0; j<NI; j++) { 4982 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 4983 if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) { 4984 intent.setPriority(0); 4985 Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity " 4986 + a.className + " with priority > 0, forcing to 0"); 4987 } 4988 if (DEBUG_SHOW_INFO) { 4989 Log.v(TAG, " IntentFilter:"); 4990 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 4991 } 4992 if (!intent.debugCheck()) { 4993 Log.w(TAG, "==> For Activity " + a.info.name); 4994 } 4995 addFilter(intent); 4996 } 4997 } 4998 4999 public final void removeActivity(PackageParser.Activity a, String type) { 5000 mActivities.remove(a.getComponentName()); 5001 if (DEBUG_SHOW_INFO) { 5002 Log.v(TAG, " " + type + " " 5003 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 5004 : a.info.name) + ":"); 5005 Log.v(TAG, " Class=" + a.info.name); 5006 } 5007 final int NI = a.intents.size(); 5008 for (int j=0; j<NI; j++) { 5009 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 5010 if (DEBUG_SHOW_INFO) { 5011 Log.v(TAG, " IntentFilter:"); 5012 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5013 } 5014 removeFilter(intent); 5015 } 5016 } 5017 5018 @Override 5019 protected boolean allowFilterResult( 5020 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 5021 ActivityInfo filterAi = filter.activity.info; 5022 for (int i=dest.size()-1; i>=0; i--) { 5023 ActivityInfo destAi = dest.get(i).activityInfo; 5024 if (destAi.name == filterAi.name 5025 && destAi.packageName == filterAi.packageName) { 5026 return false; 5027 } 5028 } 5029 return true; 5030 } 5031 5032 @Override 5033 protected ActivityIntentInfo[] newArray(int size) { 5034 return new ActivityIntentInfo[size]; 5035 } 5036 5037 @Override 5038 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 5039 if (!sUserManager.exists(userId)) return true; 5040 PackageParser.Package p = filter.activity.owner; 5041 if (p != null) { 5042 PackageSetting ps = (PackageSetting)p.mExtras; 5043 if (ps != null) { 5044 // System apps are never considered stopped for purposes of 5045 // filtering, because there may be no way for the user to 5046 // actually re-launch them. 5047 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 5048 && ps.getStopped(userId); 5049 } 5050 } 5051 return false; 5052 } 5053 5054 @Override 5055 protected String packageForFilter(PackageParser.ActivityIntentInfo info) { 5056 return info.activity.owner.packageName; 5057 } 5058 5059 @Override 5060 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 5061 int match, int userId) { 5062 if (!sUserManager.exists(userId)) return null; 5063 if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) { 5064 return null; 5065 } 5066 final PackageParser.Activity activity = info.activity; 5067 if (mSafeMode && (activity.info.applicationInfo.flags 5068 &ApplicationInfo.FLAG_SYSTEM) == 0) { 5069 return null; 5070 } 5071 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 5072 if (ps == null) { 5073 return null; 5074 } 5075 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 5076 ps.readUserState(userId), userId); 5077 if (ai == null) { 5078 return null; 5079 } 5080 final ResolveInfo res = new ResolveInfo(); 5081 res.activityInfo = ai; 5082 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 5083 res.filter = info; 5084 } 5085 res.priority = info.getPriority(); 5086 res.preferredOrder = activity.owner.mPreferredOrder; 5087 //System.out.println("Result: " + res.activityInfo.className + 5088 // " = " + res.priority); 5089 res.match = match; 5090 res.isDefault = info.hasDefault; 5091 res.labelRes = info.labelRes; 5092 res.nonLocalizedLabel = info.nonLocalizedLabel; 5093 res.icon = info.icon; 5094 res.system = isSystemApp(res.activityInfo.applicationInfo); 5095 return res; 5096 } 5097 5098 @Override 5099 protected void sortResults(List<ResolveInfo> results) { 5100 Collections.sort(results, mResolvePrioritySorter); 5101 } 5102 5103 @Override 5104 protected void dumpFilter(PrintWriter out, String prefix, 5105 PackageParser.ActivityIntentInfo filter) { 5106 out.print(prefix); out.print( 5107 Integer.toHexString(System.identityHashCode(filter.activity))); 5108 out.print(' '); 5109 out.print(filter.activity.getComponentShortName()); 5110 out.print(" filter "); 5111 out.println(Integer.toHexString(System.identityHashCode(filter))); 5112 } 5113 5114// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 5115// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 5116// final List<ResolveInfo> retList = Lists.newArrayList(); 5117// while (i.hasNext()) { 5118// final ResolveInfo resolveInfo = i.next(); 5119// if (isEnabledLP(resolveInfo.activityInfo)) { 5120// retList.add(resolveInfo); 5121// } 5122// } 5123// return retList; 5124// } 5125 5126 // Keys are String (activity class name), values are Activity. 5127 private final HashMap<ComponentName, PackageParser.Activity> mActivities 5128 = new HashMap<ComponentName, PackageParser.Activity>(); 5129 private int mFlags; 5130 } 5131 5132 private final class ServiceIntentResolver 5133 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 5134 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 5135 boolean defaultOnly, int userId) { 5136 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 5137 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 5138 } 5139 5140 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 5141 int userId) { 5142 if (!sUserManager.exists(userId)) return null; 5143 mFlags = flags; 5144 return super.queryIntent(intent, resolvedType, 5145 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 5146 } 5147 5148 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 5149 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 5150 if (!sUserManager.exists(userId)) return null; 5151 if (packageServices == null) { 5152 return null; 5153 } 5154 mFlags = flags; 5155 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 5156 final int N = packageServices.size(); 5157 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 5158 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 5159 5160 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 5161 for (int i = 0; i < N; ++i) { 5162 intentFilters = packageServices.get(i).intents; 5163 if (intentFilters != null && intentFilters.size() > 0) { 5164 PackageParser.ServiceIntentInfo[] array = 5165 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 5166 intentFilters.toArray(array); 5167 listCut.add(array); 5168 } 5169 } 5170 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 5171 } 5172 5173 public final void addService(PackageParser.Service s) { 5174 mServices.put(s.getComponentName(), s); 5175 if (DEBUG_SHOW_INFO) { 5176 Log.v(TAG, " " 5177 + (s.info.nonLocalizedLabel != null 5178 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 5179 Log.v(TAG, " Class=" + s.info.name); 5180 } 5181 final int NI = s.intents.size(); 5182 int j; 5183 for (j=0; j<NI; j++) { 5184 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 5185 if (DEBUG_SHOW_INFO) { 5186 Log.v(TAG, " IntentFilter:"); 5187 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5188 } 5189 if (!intent.debugCheck()) { 5190 Log.w(TAG, "==> For Service " + s.info.name); 5191 } 5192 addFilter(intent); 5193 } 5194 } 5195 5196 public final void removeService(PackageParser.Service s) { 5197 mServices.remove(s.getComponentName()); 5198 if (DEBUG_SHOW_INFO) { 5199 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 5200 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 5201 Log.v(TAG, " Class=" + s.info.name); 5202 } 5203 final int NI = s.intents.size(); 5204 int j; 5205 for (j=0; j<NI; j++) { 5206 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 5207 if (DEBUG_SHOW_INFO) { 5208 Log.v(TAG, " IntentFilter:"); 5209 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 5210 } 5211 removeFilter(intent); 5212 } 5213 } 5214 5215 @Override 5216 protected boolean allowFilterResult( 5217 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 5218 ServiceInfo filterSi = filter.service.info; 5219 for (int i=dest.size()-1; i>=0; i--) { 5220 ServiceInfo destAi = dest.get(i).serviceInfo; 5221 if (destAi.name == filterSi.name 5222 && destAi.packageName == filterSi.packageName) { 5223 return false; 5224 } 5225 } 5226 return true; 5227 } 5228 5229 @Override 5230 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 5231 return new PackageParser.ServiceIntentInfo[size]; 5232 } 5233 5234 @Override 5235 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 5236 if (!sUserManager.exists(userId)) return true; 5237 PackageParser.Package p = filter.service.owner; 5238 if (p != null) { 5239 PackageSetting ps = (PackageSetting)p.mExtras; 5240 if (ps != null) { 5241 // System apps are never considered stopped for purposes of 5242 // filtering, because there may be no way for the user to 5243 // actually re-launch them. 5244 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 5245 && ps.getStopped(userId); 5246 } 5247 } 5248 return false; 5249 } 5250 5251 @Override 5252 protected String packageForFilter(PackageParser.ServiceIntentInfo info) { 5253 return info.service.owner.packageName; 5254 } 5255 5256 @Override 5257 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 5258 int match, int userId) { 5259 if (!sUserManager.exists(userId)) return null; 5260 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 5261 if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) { 5262 return null; 5263 } 5264 final PackageParser.Service service = info.service; 5265 if (mSafeMode && (service.info.applicationInfo.flags 5266 &ApplicationInfo.FLAG_SYSTEM) == 0) { 5267 return null; 5268 } 5269 PackageSetting ps = (PackageSetting) service.owner.mExtras; 5270 if (ps == null) { 5271 return null; 5272 } 5273 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 5274 ps.readUserState(userId), userId); 5275 if (si == null) { 5276 return null; 5277 } 5278 final ResolveInfo res = new ResolveInfo(); 5279 res.serviceInfo = si; 5280 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 5281 res.filter = filter; 5282 } 5283 res.priority = info.getPriority(); 5284 res.preferredOrder = service.owner.mPreferredOrder; 5285 //System.out.println("Result: " + res.activityInfo.className + 5286 // " = " + res.priority); 5287 res.match = match; 5288 res.isDefault = info.hasDefault; 5289 res.labelRes = info.labelRes; 5290 res.nonLocalizedLabel = info.nonLocalizedLabel; 5291 res.icon = info.icon; 5292 res.system = isSystemApp(res.serviceInfo.applicationInfo); 5293 return res; 5294 } 5295 5296 @Override 5297 protected void sortResults(List<ResolveInfo> results) { 5298 Collections.sort(results, mResolvePrioritySorter); 5299 } 5300 5301 @Override 5302 protected void dumpFilter(PrintWriter out, String prefix, 5303 PackageParser.ServiceIntentInfo filter) { 5304 out.print(prefix); out.print( 5305 Integer.toHexString(System.identityHashCode(filter.service))); 5306 out.print(' '); 5307 out.print(filter.service.getComponentShortName()); 5308 out.print(" filter "); 5309 out.println(Integer.toHexString(System.identityHashCode(filter))); 5310 } 5311 5312// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 5313// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 5314// final List<ResolveInfo> retList = Lists.newArrayList(); 5315// while (i.hasNext()) { 5316// final ResolveInfo resolveInfo = (ResolveInfo) i; 5317// if (isEnabledLP(resolveInfo.serviceInfo)) { 5318// retList.add(resolveInfo); 5319// } 5320// } 5321// return retList; 5322// } 5323 5324 // Keys are String (activity class name), values are Activity. 5325 private final HashMap<ComponentName, PackageParser.Service> mServices 5326 = new HashMap<ComponentName, PackageParser.Service>(); 5327 private int mFlags; 5328 }; 5329 5330 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 5331 new Comparator<ResolveInfo>() { 5332 public int compare(ResolveInfo r1, ResolveInfo r2) { 5333 int v1 = r1.priority; 5334 int v2 = r2.priority; 5335 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 5336 if (v1 != v2) { 5337 return (v1 > v2) ? -1 : 1; 5338 } 5339 v1 = r1.preferredOrder; 5340 v2 = r2.preferredOrder; 5341 if (v1 != v2) { 5342 return (v1 > v2) ? -1 : 1; 5343 } 5344 if (r1.isDefault != r2.isDefault) { 5345 return r1.isDefault ? -1 : 1; 5346 } 5347 v1 = r1.match; 5348 v2 = r2.match; 5349 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 5350 if (v1 != v2) { 5351 return (v1 > v2) ? -1 : 1; 5352 } 5353 if (r1.system != r2.system) { 5354 return r1.system ? -1 : 1; 5355 } 5356 return 0; 5357 } 5358 }; 5359 5360 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 5361 new Comparator<ProviderInfo>() { 5362 public int compare(ProviderInfo p1, ProviderInfo p2) { 5363 final int v1 = p1.initOrder; 5364 final int v2 = p2.initOrder; 5365 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 5366 } 5367 }; 5368 5369 static final void sendPackageBroadcast(String action, String pkg, 5370 Bundle extras, String targetPkg, IIntentReceiver finishedReceiver, 5371 int[] userIds) { 5372 IActivityManager am = ActivityManagerNative.getDefault(); 5373 if (am != null) { 5374 try { 5375 if (userIds == null) { 5376 userIds = am.getRunningUserIds(); 5377 } 5378 for (int id : userIds) { 5379 final Intent intent = new Intent(action, 5380 pkg != null ? Uri.fromParts("package", pkg, null) : null); 5381 if (extras != null) { 5382 intent.putExtras(extras); 5383 } 5384 if (targetPkg != null) { 5385 intent.setPackage(targetPkg); 5386 } 5387 // Modify the UID when posting to other users 5388 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 5389 if (uid > 0 && UserHandle.getUserId(uid) != id) { 5390 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 5391 intent.putExtra(Intent.EXTRA_UID, uid); 5392 } 5393 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 5394 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 5395 if (DEBUG_BROADCASTS) { 5396 RuntimeException here = new RuntimeException("here"); 5397 here.fillInStackTrace(); 5398 Slog.d(TAG, "Sending to user " + id + ": " 5399 + intent.toShortString(false, true, false, false) 5400 + " " + intent.getExtras(), here); 5401 } 5402 am.broadcastIntent(null, intent, null, finishedReceiver, 5403 0, null, null, null, finishedReceiver != null, false, id); 5404 } 5405 } catch (RemoteException ex) { 5406 } 5407 } 5408 } 5409 5410 /** 5411 * Check if the external storage media is available. This is true if there 5412 * is a mounted external storage medium or if the external storage is 5413 * emulated. 5414 */ 5415 private boolean isExternalMediaAvailable() { 5416 return mMediaMounted || Environment.isExternalStorageEmulated(); 5417 } 5418 5419 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 5420 // writer 5421 synchronized (mPackages) { 5422 if (!isExternalMediaAvailable()) { 5423 // If the external storage is no longer mounted at this point, 5424 // the caller may not have been able to delete all of this 5425 // packages files and can not delete any more. Bail. 5426 return null; 5427 } 5428 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 5429 if (lastPackage != null) { 5430 pkgs.remove(lastPackage); 5431 } 5432 if (pkgs.size() > 0) { 5433 return pkgs.get(0); 5434 } 5435 } 5436 return null; 5437 } 5438 5439 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 5440 if (false) { 5441 RuntimeException here = new RuntimeException("here"); 5442 here.fillInStackTrace(); 5443 Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId 5444 + " andCode=" + andCode, here); 5445 } 5446 mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE, 5447 userId, andCode ? 1 : 0, packageName)); 5448 } 5449 5450 void startCleaningPackages() { 5451 // reader 5452 synchronized (mPackages) { 5453 if (!isExternalMediaAvailable()) { 5454 return; 5455 } 5456 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 5457 return; 5458 } 5459 } 5460 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 5461 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 5462 IActivityManager am = ActivityManagerNative.getDefault(); 5463 if (am != null) { 5464 try { 5465 am.startService(null, intent, null, UserHandle.USER_OWNER); 5466 } catch (RemoteException e) { 5467 } 5468 } 5469 } 5470 5471 private final class AppDirObserver extends FileObserver { 5472 public AppDirObserver(String path, int mask, boolean isrom) { 5473 super(path, mask); 5474 mRootDir = path; 5475 mIsRom = isrom; 5476 } 5477 5478 public void onEvent(int event, String path) { 5479 String removedPackage = null; 5480 int removedAppId = -1; 5481 int[] removedUsers = null; 5482 String addedPackage = null; 5483 int addedAppId = -1; 5484 int[] addedUsers = null; 5485 5486 // TODO post a message to the handler to obtain serial ordering 5487 synchronized (mInstallLock) { 5488 String fullPathStr = null; 5489 File fullPath = null; 5490 if (path != null) { 5491 fullPath = new File(mRootDir, path); 5492 fullPathStr = fullPath.getPath(); 5493 } 5494 5495 if (DEBUG_APP_DIR_OBSERVER) 5496 Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event)); 5497 5498 if (!isPackageFilename(path)) { 5499 if (DEBUG_APP_DIR_OBSERVER) 5500 Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr); 5501 return; 5502 } 5503 5504 // Ignore packages that are being installed or 5505 // have just been installed. 5506 if (ignoreCodePath(fullPathStr)) { 5507 return; 5508 } 5509 PackageParser.Package p = null; 5510 PackageSetting ps = null; 5511 // reader 5512 synchronized (mPackages) { 5513 p = mAppDirs.get(fullPathStr); 5514 if (p != null) { 5515 ps = mSettings.mPackages.get(p.applicationInfo.packageName); 5516 if (ps != null) { 5517 removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 5518 } else { 5519 removedUsers = sUserManager.getUserIds(); 5520 } 5521 } 5522 addedUsers = sUserManager.getUserIds(); 5523 } 5524 if ((event&REMOVE_EVENTS) != 0) { 5525 if (ps != null) { 5526 removePackageLI(ps, true); 5527 removedPackage = ps.name; 5528 removedAppId = ps.appId; 5529 } 5530 } 5531 5532 if ((event&ADD_EVENTS) != 0) { 5533 if (p == null) { 5534 p = scanPackageLI(fullPath, 5535 (mIsRom ? PackageParser.PARSE_IS_SYSTEM 5536 | PackageParser.PARSE_IS_SYSTEM_DIR: 0) | 5537 PackageParser.PARSE_CHATTY | 5538 PackageParser.PARSE_MUST_BE_APK, 5539 SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME, 5540 System.currentTimeMillis(), UserHandle.ALL); 5541 if (p != null) { 5542 /* 5543 * TODO this seems dangerous as the package may have 5544 * changed since we last acquired the mPackages 5545 * lock. 5546 */ 5547 // writer 5548 synchronized (mPackages) { 5549 updatePermissionsLPw(p.packageName, p, 5550 p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0); 5551 } 5552 addedPackage = p.applicationInfo.packageName; 5553 addedAppId = UserHandle.getAppId(p.applicationInfo.uid); 5554 } 5555 } 5556 } 5557 5558 // reader 5559 synchronized (mPackages) { 5560 mSettings.writeLPr(); 5561 } 5562 } 5563 5564 if (removedPackage != null) { 5565 Bundle extras = new Bundle(1); 5566 extras.putInt(Intent.EXTRA_UID, removedAppId); 5567 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false); 5568 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 5569 extras, null, null, removedUsers); 5570 } 5571 if (addedPackage != null) { 5572 Bundle extras = new Bundle(1); 5573 extras.putInt(Intent.EXTRA_UID, addedAppId); 5574 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage, 5575 extras, null, null, addedUsers); 5576 } 5577 } 5578 5579 private final String mRootDir; 5580 private final boolean mIsRom; 5581 } 5582 5583 /* Called when a downloaded package installation has been confirmed by the user */ 5584 public void installPackage( 5585 final Uri packageURI, final IPackageInstallObserver observer, final int flags) { 5586 installPackage(packageURI, observer, flags, null); 5587 } 5588 5589 /* Called when a downloaded package installation has been confirmed by the user */ 5590 public void installPackage( 5591 final Uri packageURI, final IPackageInstallObserver observer, final int flags, 5592 final String installerPackageName) { 5593 installPackageWithVerification(packageURI, observer, flags, installerPackageName, null, 5594 null, null); 5595 } 5596 5597 @Override 5598 public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer, 5599 int flags, String installerPackageName, Uri verificationURI, 5600 ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) { 5601 VerificationParams verificationParams = new VerificationParams(verificationURI, null, null, 5602 VerificationParams.NO_UID, manifestDigest); 5603 installPackageWithVerificationAndEncryption(packageURI, observer, flags, 5604 installerPackageName, verificationParams, encryptionParams); 5605 } 5606 5607 public void installPackageWithVerificationAndEncryption(Uri packageURI, 5608 IPackageInstallObserver observer, int flags, String installerPackageName, 5609 VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) { 5610 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 5611 null); 5612 5613 final int uid = Binder.getCallingUid(); 5614 UserHandle user; 5615 if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) { 5616 user = UserHandle.ALL; 5617 } else { 5618 user = new UserHandle(UserHandle.getUserId(uid)); 5619 } 5620 5621 final int filteredFlags; 5622 5623 if (uid == Process.SHELL_UID || uid == 0) { 5624 if (DEBUG_INSTALL) { 5625 Slog.v(TAG, "Install from ADB"); 5626 } 5627 filteredFlags = flags | PackageManager.INSTALL_FROM_ADB; 5628 } else { 5629 filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB; 5630 } 5631 5632 verificationParams.setInstallerUid(uid); 5633 5634 final Message msg = mHandler.obtainMessage(INIT_COPY); 5635 msg.obj = new InstallParams(packageURI, observer, filteredFlags, installerPackageName, 5636 verificationParams, encryptionParams, user); 5637 mHandler.sendMessage(msg); 5638 } 5639 5640 /** 5641 * @hide 5642 */ 5643 @Override 5644 public int installExistingPackage(String packageName) { 5645 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 5646 null); 5647 PackageSetting pkgSetting; 5648 final int uid = Binder.getCallingUid(); 5649 final int userId = UserHandle.getUserId(uid); 5650 5651 long callingId = Binder.clearCallingIdentity(); 5652 try { 5653 boolean sendAdded = false; 5654 Bundle extras = new Bundle(1); 5655 5656 // writer 5657 synchronized (mPackages) { 5658 pkgSetting = mSettings.mPackages.get(packageName); 5659 if (pkgSetting == null) { 5660 return PackageManager.INSTALL_FAILED_INVALID_URI; 5661 } 5662 if (!pkgSetting.getInstalled(userId)) { 5663 pkgSetting.setInstalled(true, userId); 5664 mSettings.writePackageRestrictionsLPr(userId); 5665 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId)); 5666 sendAdded = true; 5667 } 5668 } 5669 5670 if (sendAdded) { 5671 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 5672 packageName, extras, null, null, new int[] {userId}); 5673 } 5674 } finally { 5675 Binder.restoreCallingIdentity(callingId); 5676 } 5677 5678 return PackageManager.INSTALL_SUCCEEDED; 5679 } 5680 5681 @Override 5682 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 5683 mContext.enforceCallingOrSelfPermission( 5684 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 5685 "Only package verification agents can verify applications"); 5686 5687 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 5688 final PackageVerificationResponse response = new PackageVerificationResponse( 5689 verificationCode, Binder.getCallingUid()); 5690 msg.arg1 = id; 5691 msg.obj = response; 5692 mHandler.sendMessage(msg); 5693 } 5694 5695 @Override 5696 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 5697 long millisecondsToDelay) { 5698 mContext.enforceCallingOrSelfPermission( 5699 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 5700 "Only package verification agents can extend verification timeouts"); 5701 5702 final PackageVerificationState state = mPendingVerification.get(id); 5703 final PackageVerificationResponse response = new PackageVerificationResponse( 5704 verificationCodeAtTimeout, Binder.getCallingUid()); 5705 5706 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 5707 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 5708 } 5709 if (millisecondsToDelay < 0) { 5710 millisecondsToDelay = 0; 5711 } 5712 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 5713 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 5714 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 5715 } 5716 5717 if ((state != null) && !state.timeoutExtended()) { 5718 state.extendTimeout(); 5719 5720 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 5721 msg.arg1 = id; 5722 msg.obj = response; 5723 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 5724 } 5725 } 5726 5727 private void broadcastPackageVerified(int verificationId, Uri packageUri, 5728 int verificationCode, UserHandle user) { 5729 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 5730 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 5731 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 5732 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 5733 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 5734 5735 mContext.sendBroadcastAsUser(intent, user, 5736 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 5737 } 5738 5739 private ComponentName matchComponentForVerifier(String packageName, 5740 List<ResolveInfo> receivers) { 5741 ActivityInfo targetReceiver = null; 5742 5743 final int NR = receivers.size(); 5744 for (int i = 0; i < NR; i++) { 5745 final ResolveInfo info = receivers.get(i); 5746 if (info.activityInfo == null) { 5747 continue; 5748 } 5749 5750 if (packageName.equals(info.activityInfo.packageName)) { 5751 targetReceiver = info.activityInfo; 5752 break; 5753 } 5754 } 5755 5756 if (targetReceiver == null) { 5757 return null; 5758 } 5759 5760 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 5761 } 5762 5763 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 5764 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 5765 if (pkgInfo.verifiers.length == 0) { 5766 return null; 5767 } 5768 5769 final int N = pkgInfo.verifiers.length; 5770 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 5771 for (int i = 0; i < N; i++) { 5772 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 5773 5774 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 5775 receivers); 5776 if (comp == null) { 5777 continue; 5778 } 5779 5780 final int verifierUid = getUidForVerifier(verifierInfo); 5781 if (verifierUid == -1) { 5782 continue; 5783 } 5784 5785 if (DEBUG_VERIFY) { 5786 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 5787 + " with the correct signature"); 5788 } 5789 sufficientVerifiers.add(comp); 5790 verificationState.addSufficientVerifier(verifierUid); 5791 } 5792 5793 return sufficientVerifiers; 5794 } 5795 5796 private int getUidForVerifier(VerifierInfo verifierInfo) { 5797 synchronized (mPackages) { 5798 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 5799 if (pkg == null) { 5800 return -1; 5801 } else if (pkg.mSignatures.length != 1) { 5802 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 5803 + " has more than one signature; ignoring"); 5804 return -1; 5805 } 5806 5807 /* 5808 * If the public key of the package's signature does not match 5809 * our expected public key, then this is a different package and 5810 * we should skip. 5811 */ 5812 5813 final byte[] expectedPublicKey; 5814 try { 5815 final Signature verifierSig = pkg.mSignatures[0]; 5816 final PublicKey publicKey = verifierSig.getPublicKey(); 5817 expectedPublicKey = publicKey.getEncoded(); 5818 } catch (CertificateException e) { 5819 return -1; 5820 } 5821 5822 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 5823 5824 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 5825 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 5826 + " does not have the expected public key; ignoring"); 5827 return -1; 5828 } 5829 5830 return pkg.applicationInfo.uid; 5831 } 5832 } 5833 5834 public void finishPackageInstall(int token) { 5835 enforceSystemOrRoot("Only the system is allowed to finish installs"); 5836 5837 if (DEBUG_INSTALL) { 5838 Slog.v(TAG, "BM finishing package install for " + token); 5839 } 5840 5841 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 5842 mHandler.sendMessage(msg); 5843 } 5844 5845 /** 5846 * Get the verification agent timeout. 5847 * 5848 * @return verification timeout in milliseconds 5849 */ 5850 private long getVerificationTimeout() { 5851 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 5852 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 5853 DEFAULT_VERIFICATION_TIMEOUT); 5854 } 5855 5856 /** 5857 * Get the default verification agent response code. 5858 * 5859 * @return default verification response code 5860 */ 5861 private int getDefaultVerificationResponse() { 5862 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 5863 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 5864 DEFAULT_VERIFICATION_RESPONSE); 5865 } 5866 5867 /** 5868 * Check whether or not package verification has been enabled. 5869 * 5870 * @return true if verification should be performed 5871 */ 5872 private boolean isVerificationEnabled(int flags) { 5873 if (!DEFAULT_VERIFY_ENABLE) { 5874 return false; 5875 } 5876 5877 // Check if installing from ADB 5878 if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) { 5879 // Do not run verification in a test harness environment 5880 if (ActivityManager.isRunningInTestHarness()) { 5881 return false; 5882 } 5883 // Check if the developer does not want package verification for ADB installs 5884 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 5885 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 5886 return false; 5887 } 5888 } 5889 5890 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 5891 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 5892 } 5893 5894 /** 5895 * Get the "allow unknown sources" setting. 5896 * 5897 * @return the current "allow unknown sources" setting 5898 */ 5899 private int getUnknownSourcesSettings() { 5900 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 5901 android.provider.Settings.Global.INSTALL_NON_MARKET_APPS, 5902 -1); 5903 } 5904 5905 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 5906 final int uid = Binder.getCallingUid(); 5907 // writer 5908 synchronized (mPackages) { 5909 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 5910 if (targetPackageSetting == null) { 5911 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 5912 } 5913 5914 PackageSetting installerPackageSetting; 5915 if (installerPackageName != null) { 5916 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 5917 if (installerPackageSetting == null) { 5918 throw new IllegalArgumentException("Unknown installer package: " 5919 + installerPackageName); 5920 } 5921 } else { 5922 installerPackageSetting = null; 5923 } 5924 5925 Signature[] callerSignature; 5926 Object obj = mSettings.getUserIdLPr(uid); 5927 if (obj != null) { 5928 if (obj instanceof SharedUserSetting) { 5929 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 5930 } else if (obj instanceof PackageSetting) { 5931 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 5932 } else { 5933 throw new SecurityException("Bad object " + obj + " for uid " + uid); 5934 } 5935 } else { 5936 throw new SecurityException("Unknown calling uid " + uid); 5937 } 5938 5939 // Verify: can't set installerPackageName to a package that is 5940 // not signed with the same cert as the caller. 5941 if (installerPackageSetting != null) { 5942 if (compareSignatures(callerSignature, 5943 installerPackageSetting.signatures.mSignatures) 5944 != PackageManager.SIGNATURE_MATCH) { 5945 throw new SecurityException( 5946 "Caller does not have same cert as new installer package " 5947 + installerPackageName); 5948 } 5949 } 5950 5951 // Verify: if target already has an installer package, it must 5952 // be signed with the same cert as the caller. 5953 if (targetPackageSetting.installerPackageName != null) { 5954 PackageSetting setting = mSettings.mPackages.get( 5955 targetPackageSetting.installerPackageName); 5956 // If the currently set package isn't valid, then it's always 5957 // okay to change it. 5958 if (setting != null) { 5959 if (compareSignatures(callerSignature, 5960 setting.signatures.mSignatures) 5961 != PackageManager.SIGNATURE_MATCH) { 5962 throw new SecurityException( 5963 "Caller does not have same cert as old installer package " 5964 + targetPackageSetting.installerPackageName); 5965 } 5966 } 5967 } 5968 5969 // Okay! 5970 targetPackageSetting.installerPackageName = installerPackageName; 5971 scheduleWriteSettingsLocked(); 5972 } 5973 } 5974 5975 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 5976 // Queue up an async operation since the package installation may take a little while. 5977 mHandler.post(new Runnable() { 5978 public void run() { 5979 mHandler.removeCallbacks(this); 5980 // Result object to be returned 5981 PackageInstalledInfo res = new PackageInstalledInfo(); 5982 res.returnCode = currentStatus; 5983 res.uid = -1; 5984 res.pkg = null; 5985 res.removedInfo = new PackageRemovedInfo(); 5986 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 5987 args.doPreInstall(res.returnCode); 5988 synchronized (mInstallLock) { 5989 installPackageLI(args, true, res); 5990 } 5991 args.doPostInstall(res.returnCode, res.uid); 5992 } 5993 5994 // A restore should be performed at this point if (a) the install 5995 // succeeded, (b) the operation is not an update, and (c) the new 5996 // package has a backupAgent defined. 5997 final boolean update = res.removedInfo.removedPackage != null; 5998 boolean doRestore = (!update 5999 && res.pkg != null 6000 && res.pkg.applicationInfo.backupAgentName != null); 6001 6002 // Set up the post-install work request bookkeeping. This will be used 6003 // and cleaned up by the post-install event handling regardless of whether 6004 // there's a restore pass performed. Token values are >= 1. 6005 int token; 6006 if (mNextInstallToken < 0) mNextInstallToken = 1; 6007 token = mNextInstallToken++; 6008 6009 PostInstallData data = new PostInstallData(args, res); 6010 mRunningInstalls.put(token, data); 6011 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 6012 6013 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 6014 // Pass responsibility to the Backup Manager. It will perform a 6015 // restore if appropriate, then pass responsibility back to the 6016 // Package Manager to run the post-install observer callbacks 6017 // and broadcasts. 6018 IBackupManager bm = IBackupManager.Stub.asInterface( 6019 ServiceManager.getService(Context.BACKUP_SERVICE)); 6020 if (bm != null) { 6021 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 6022 + " to BM for possible restore"); 6023 try { 6024 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 6025 } catch (RemoteException e) { 6026 // can't happen; the backup manager is local 6027 } catch (Exception e) { 6028 Slog.e(TAG, "Exception trying to enqueue restore", e); 6029 doRestore = false; 6030 } 6031 } else { 6032 Slog.e(TAG, "Backup Manager not found!"); 6033 doRestore = false; 6034 } 6035 } 6036 6037 if (!doRestore) { 6038 // No restore possible, or the Backup Manager was mysteriously not 6039 // available -- just fire the post-install work request directly. 6040 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 6041 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 6042 mHandler.sendMessage(msg); 6043 } 6044 } 6045 }); 6046 } 6047 6048 private abstract class HandlerParams { 6049 private static final int MAX_RETRIES = 4; 6050 6051 /** 6052 * Number of times startCopy() has been attempted and had a non-fatal 6053 * error. 6054 */ 6055 private int mRetries = 0; 6056 6057 /** User handle for the user requesting the information or installation. */ 6058 private final UserHandle mUser; 6059 6060 HandlerParams(UserHandle user) { 6061 mUser = user; 6062 } 6063 6064 UserHandle getUser() { 6065 return mUser; 6066 } 6067 6068 final boolean startCopy() { 6069 boolean res; 6070 try { 6071 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy"); 6072 6073 if (++mRetries > MAX_RETRIES) { 6074 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 6075 mHandler.sendEmptyMessage(MCS_GIVE_UP); 6076 handleServiceError(); 6077 return false; 6078 } else { 6079 handleStartCopy(); 6080 res = true; 6081 } 6082 } catch (RemoteException e) { 6083 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 6084 mHandler.sendEmptyMessage(MCS_RECONNECT); 6085 res = false; 6086 } 6087 handleReturnCode(); 6088 return res; 6089 } 6090 6091 final void serviceError() { 6092 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 6093 handleServiceError(); 6094 handleReturnCode(); 6095 } 6096 6097 abstract void handleStartCopy() throws RemoteException; 6098 abstract void handleServiceError(); 6099 abstract void handleReturnCode(); 6100 } 6101 6102 class MeasureParams extends HandlerParams { 6103 private final PackageStats mStats; 6104 private boolean mSuccess; 6105 6106 private final IPackageStatsObserver mObserver; 6107 6108 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 6109 super(new UserHandle(stats.userHandle)); 6110 mObserver = observer; 6111 mStats = stats; 6112 } 6113 6114 @Override 6115 void handleStartCopy() throws RemoteException { 6116 synchronized (mInstallLock) { 6117 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 6118 } 6119 6120 final boolean mounted; 6121 if (Environment.isExternalStorageEmulated()) { 6122 mounted = true; 6123 } else { 6124 final String status = Environment.getExternalStorageState(); 6125 mounted = (Environment.MEDIA_MOUNTED.equals(status) 6126 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 6127 } 6128 6129 if (mounted) { 6130 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 6131 6132 final File externalCacheDir = userEnv 6133 .getExternalStorageAppCacheDirectory(mStats.packageName); 6134 final long externalCacheSize = mContainerService 6135 .calculateDirectorySize(externalCacheDir.getPath()); 6136 mStats.externalCacheSize = externalCacheSize; 6137 6138 final File externalDataDir = userEnv 6139 .getExternalStorageAppDataDirectory(mStats.packageName); 6140 long externalDataSize = mContainerService.calculateDirectorySize(externalDataDir 6141 .getPath()); 6142 6143 if (externalCacheDir.getParentFile().equals(externalDataDir)) { 6144 externalDataSize -= externalCacheSize; 6145 } 6146 mStats.externalDataSize = externalDataSize; 6147 6148 final File externalMediaDir = userEnv 6149 .getExternalStorageAppMediaDirectory(mStats.packageName); 6150 mStats.externalMediaSize = mContainerService 6151 .calculateDirectorySize(externalMediaDir.getPath()); 6152 6153 final File externalObbDir = userEnv 6154 .getExternalStorageAppObbDirectory(mStats.packageName); 6155 mStats.externalObbSize = mContainerService.calculateDirectorySize(externalObbDir 6156 .getPath()); 6157 } 6158 } 6159 6160 @Override 6161 void handleReturnCode() { 6162 if (mObserver != null) { 6163 try { 6164 mObserver.onGetStatsCompleted(mStats, mSuccess); 6165 } catch (RemoteException e) { 6166 Slog.i(TAG, "Observer no longer exists."); 6167 } 6168 } 6169 } 6170 6171 @Override 6172 void handleServiceError() { 6173 Slog.e(TAG, "Could not measure application " + mStats.packageName 6174 + " external storage"); 6175 } 6176 } 6177 6178 class InstallParams extends HandlerParams { 6179 final IPackageInstallObserver observer; 6180 int flags; 6181 6182 private final Uri mPackageURI; 6183 final String installerPackageName; 6184 final VerificationParams verificationParams; 6185 private InstallArgs mArgs; 6186 private int mRet; 6187 private File mTempPackage; 6188 final ContainerEncryptionParams encryptionParams; 6189 6190 InstallParams(Uri packageURI, 6191 IPackageInstallObserver observer, int flags, 6192 String installerPackageName, VerificationParams verificationParams, 6193 ContainerEncryptionParams encryptionParams, UserHandle user) { 6194 super(user); 6195 this.mPackageURI = packageURI; 6196 this.flags = flags; 6197 this.observer = observer; 6198 this.installerPackageName = installerPackageName; 6199 this.verificationParams = verificationParams; 6200 this.encryptionParams = encryptionParams; 6201 } 6202 6203 public ManifestDigest getManifestDigest() { 6204 if (verificationParams == null) { 6205 return null; 6206 } 6207 return verificationParams.getManifestDigest(); 6208 } 6209 6210 private int installLocationPolicy(PackageInfoLite pkgLite, int flags) { 6211 String packageName = pkgLite.packageName; 6212 int installLocation = pkgLite.installLocation; 6213 boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 6214 // reader 6215 synchronized (mPackages) { 6216 PackageParser.Package pkg = mPackages.get(packageName); 6217 if (pkg != null) { 6218 if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 6219 // Check for downgrading. 6220 if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) { 6221 if (pkgLite.versionCode < pkg.mVersionCode) { 6222 Slog.w(TAG, "Can't install update of " + packageName 6223 + " update version " + pkgLite.versionCode 6224 + " is older than installed version " 6225 + pkg.mVersionCode); 6226 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 6227 } 6228 } 6229 // Check for updated system application. 6230 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 6231 if (onSd) { 6232 Slog.w(TAG, "Cannot install update to system app on sdcard"); 6233 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 6234 } 6235 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6236 } else { 6237 if (onSd) { 6238 // Install flag overrides everything. 6239 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6240 } 6241 // If current upgrade specifies particular preference 6242 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 6243 // Application explicitly specified internal. 6244 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6245 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 6246 // App explictly prefers external. Let policy decide 6247 } else { 6248 // Prefer previous location 6249 if (isExternal(pkg)) { 6250 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6251 } 6252 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 6253 } 6254 } 6255 } else { 6256 // Invalid install. Return error code 6257 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 6258 } 6259 } 6260 } 6261 // All the special cases have been taken care of. 6262 // Return result based on recommended install location. 6263 if (onSd) { 6264 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 6265 } 6266 return pkgLite.recommendedInstallLocation; 6267 } 6268 6269 /* 6270 * Invoke remote method to get package information and install 6271 * location values. Override install location based on default 6272 * policy if needed and then create install arguments based 6273 * on the install location. 6274 */ 6275 public void handleStartCopy() throws RemoteException { 6276 int ret = PackageManager.INSTALL_SUCCEEDED; 6277 final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0; 6278 final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0; 6279 PackageInfoLite pkgLite = null; 6280 6281 if (onInt && onSd) { 6282 // Check if both bits are set. 6283 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 6284 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 6285 } else { 6286 final long lowThreshold; 6287 6288 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 6289 .getService(DeviceStorageMonitorService.SERVICE); 6290 if (dsm == null) { 6291 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 6292 lowThreshold = 0L; 6293 } else { 6294 lowThreshold = dsm.getMemoryLowThreshold(); 6295 } 6296 6297 try { 6298 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI, 6299 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6300 6301 final File packageFile; 6302 if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) { 6303 ParcelFileDescriptor out = null; 6304 6305 mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir); 6306 if (mTempPackage != null) { 6307 try { 6308 out = ParcelFileDescriptor.open(mTempPackage, 6309 ParcelFileDescriptor.MODE_READ_WRITE); 6310 } catch (FileNotFoundException e) { 6311 Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI); 6312 } 6313 6314 // Make a temporary file for decryption. 6315 ret = mContainerService 6316 .copyResource(mPackageURI, encryptionParams, out); 6317 6318 packageFile = mTempPackage; 6319 6320 FileUtils.setPermissions(packageFile.getAbsolutePath(), 6321 FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP 6322 | FileUtils.S_IROTH, 6323 -1, -1); 6324 } else { 6325 packageFile = null; 6326 } 6327 } else { 6328 packageFile = new File(mPackageURI.getPath()); 6329 } 6330 6331 if (packageFile != null) { 6332 // Remote call to find out default install location 6333 final String packageFilePath = packageFile.getAbsolutePath(); 6334 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags, 6335 lowThreshold); 6336 6337 /* 6338 * If we have too little free space, try to free cache 6339 * before giving up. 6340 */ 6341 if (pkgLite.recommendedInstallLocation 6342 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 6343 final long size = mContainerService.calculateInstalledSize( 6344 packageFilePath, isForwardLocked()); 6345 if (mInstaller.freeCache(size + lowThreshold) >= 0) { 6346 pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, 6347 flags, lowThreshold); 6348 } 6349 } 6350 } 6351 } finally { 6352 mContext.revokeUriPermission(mPackageURI, 6353 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6354 } 6355 } 6356 6357 if (ret == PackageManager.INSTALL_SUCCEEDED) { 6358 int loc = pkgLite.recommendedInstallLocation; 6359 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 6360 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 6361 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 6362 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 6363 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 6364 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6365 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 6366 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 6367 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 6368 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 6369 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 6370 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 6371 } else { 6372 // Override with defaults if needed. 6373 loc = installLocationPolicy(pkgLite, flags); 6374 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 6375 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 6376 } else if (!onSd && !onInt) { 6377 // Override install location with flags 6378 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 6379 // Set the flag to install on external media. 6380 flags |= PackageManager.INSTALL_EXTERNAL; 6381 flags &= ~PackageManager.INSTALL_INTERNAL; 6382 } else { 6383 // Make sure the flag for installing on external 6384 // media is unset 6385 flags |= PackageManager.INSTALL_INTERNAL; 6386 flags &= ~PackageManager.INSTALL_EXTERNAL; 6387 } 6388 } 6389 } 6390 } 6391 6392 final InstallArgs args = createInstallArgs(this); 6393 mArgs = args; 6394 6395 if (ret == PackageManager.INSTALL_SUCCEEDED) { 6396 /* 6397 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by 6398 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER. 6399 */ 6400 int userIdentifier = getUser().getIdentifier(); 6401 if (userIdentifier == UserHandle.USER_ALL 6402 && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) { 6403 userIdentifier = UserHandle.USER_OWNER; 6404 } 6405 6406 /* 6407 * Determine if we have any installed package verifiers. If we 6408 * do, then we'll defer to them to verify the packages. 6409 */ 6410 final int requiredUid = mRequiredVerifierPackage == null ? -1 6411 : getPackageUid(mRequiredVerifierPackage, userIdentifier); 6412 if (requiredUid != -1 && isVerificationEnabled(flags)) { 6413 final Intent verification = new Intent( 6414 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 6415 verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE); 6416 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 6417 6418 final List<ResolveInfo> receivers = queryIntentReceivers(verification, 6419 PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS, 6420 0 /* TODO: Which userId? */); 6421 6422 if (DEBUG_VERIFY) { 6423 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 6424 + verification.toString() + " with " + pkgLite.verifiers.length 6425 + " optional verifiers"); 6426 } 6427 6428 final int verificationId = mPendingVerificationToken++; 6429 6430 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 6431 6432 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 6433 installerPackageName); 6434 6435 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags); 6436 6437 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 6438 pkgLite.packageName); 6439 6440 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 6441 pkgLite.versionCode); 6442 6443 if (verificationParams != null) { 6444 if (verificationParams.getVerificationURI() != null) { 6445 verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI, 6446 verificationParams.getVerificationURI()); 6447 } 6448 if (verificationParams.getOriginatingURI() != null) { 6449 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 6450 verificationParams.getOriginatingURI()); 6451 } 6452 if (verificationParams.getReferrer() != null) { 6453 verification.putExtra(Intent.EXTRA_REFERRER, 6454 verificationParams.getReferrer()); 6455 } 6456 if (verificationParams.getOriginatingUid() >= 0) { 6457 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 6458 verificationParams.getOriginatingUid()); 6459 } 6460 if (verificationParams.getInstallerUid() >= 0) { 6461 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 6462 verificationParams.getInstallerUid()); 6463 } 6464 } 6465 6466 final PackageVerificationState verificationState = new PackageVerificationState( 6467 requiredUid, args); 6468 6469 mPendingVerification.append(verificationId, verificationState); 6470 6471 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 6472 receivers, verificationState); 6473 6474 /* 6475 * If any sufficient verifiers were listed in the package 6476 * manifest, attempt to ask them. 6477 */ 6478 if (sufficientVerifiers != null) { 6479 final int N = sufficientVerifiers.size(); 6480 if (N == 0) { 6481 Slog.i(TAG, "Additional verifiers required, but none installed."); 6482 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 6483 } else { 6484 for (int i = 0; i < N; i++) { 6485 final ComponentName verifierComponent = sufficientVerifiers.get(i); 6486 6487 final Intent sufficientIntent = new Intent(verification); 6488 sufficientIntent.setComponent(verifierComponent); 6489 6490 mContext.sendBroadcastAsUser(sufficientIntent, getUser()); 6491 } 6492 } 6493 } 6494 6495 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 6496 mRequiredVerifierPackage, receivers); 6497 if (ret == PackageManager.INSTALL_SUCCEEDED 6498 && mRequiredVerifierPackage != null) { 6499 /* 6500 * Send the intent to the required verification agent, 6501 * but only start the verification timeout after the 6502 * target BroadcastReceivers have run. 6503 */ 6504 verification.setComponent(requiredVerifierComponent); 6505 mContext.sendOrderedBroadcastAsUser(verification, getUser(), 6506 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 6507 new BroadcastReceiver() { 6508 @Override 6509 public void onReceive(Context context, Intent intent) { 6510 final Message msg = mHandler 6511 .obtainMessage(CHECK_PENDING_VERIFICATION); 6512 msg.arg1 = verificationId; 6513 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 6514 } 6515 }, null, 0, null, null); 6516 6517 /* 6518 * We don't want the copy to proceed until verification 6519 * succeeds, so null out this field. 6520 */ 6521 mArgs = null; 6522 } 6523 } else { 6524 /* 6525 * No package verification is enabled, so immediately start 6526 * the remote call to initiate copy using temporary file. 6527 */ 6528 ret = args.copyApk(mContainerService, true); 6529 } 6530 } 6531 6532 mRet = ret; 6533 } 6534 6535 @Override 6536 void handleReturnCode() { 6537 // If mArgs is null, then MCS couldn't be reached. When it 6538 // reconnects, it will try again to install. At that point, this 6539 // will succeed. 6540 if (mArgs != null) { 6541 processPendingInstall(mArgs, mRet); 6542 6543 if (mTempPackage != null) { 6544 if (!mTempPackage.delete()) { 6545 Slog.w(TAG, "Couldn't delete temporary file: " + 6546 mTempPackage.getAbsolutePath()); 6547 } 6548 } 6549 } 6550 } 6551 6552 @Override 6553 void handleServiceError() { 6554 mArgs = createInstallArgs(this); 6555 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6556 } 6557 6558 public boolean isForwardLocked() { 6559 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6560 } 6561 6562 public Uri getPackageUri() { 6563 if (mTempPackage != null) { 6564 return Uri.fromFile(mTempPackage); 6565 } else { 6566 return mPackageURI; 6567 } 6568 } 6569 } 6570 6571 /* 6572 * Utility class used in movePackage api. 6573 * srcArgs and targetArgs are not set for invalid flags and make 6574 * sure to do null checks when invoking methods on them. 6575 * We probably want to return ErrorPrams for both failed installs 6576 * and moves. 6577 */ 6578 class MoveParams extends HandlerParams { 6579 final IPackageMoveObserver observer; 6580 final int flags; 6581 final String packageName; 6582 final InstallArgs srcArgs; 6583 final InstallArgs targetArgs; 6584 int uid; 6585 int mRet; 6586 6587 MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags, 6588 String packageName, String dataDir, int uid, UserHandle user) { 6589 super(user); 6590 this.srcArgs = srcArgs; 6591 this.observer = observer; 6592 this.flags = flags; 6593 this.packageName = packageName; 6594 this.uid = uid; 6595 if (srcArgs != null) { 6596 Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath())); 6597 targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir); 6598 } else { 6599 targetArgs = null; 6600 } 6601 } 6602 6603 public void handleStartCopy() throws RemoteException { 6604 mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6605 // Check for storage space on target medium 6606 if (!targetArgs.checkFreeStorage(mContainerService)) { 6607 Log.w(TAG, "Insufficient storage to install"); 6608 return; 6609 } 6610 6611 mRet = srcArgs.doPreCopy(); 6612 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6613 return; 6614 } 6615 6616 mRet = targetArgs.copyApk(mContainerService, false); 6617 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6618 srcArgs.doPostCopy(uid); 6619 return; 6620 } 6621 6622 mRet = srcArgs.doPostCopy(uid); 6623 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6624 return; 6625 } 6626 6627 mRet = targetArgs.doPreInstall(mRet); 6628 if (mRet != PackageManager.INSTALL_SUCCEEDED) { 6629 return; 6630 } 6631 6632 if (DEBUG_SD_INSTALL) { 6633 StringBuilder builder = new StringBuilder(); 6634 if (srcArgs != null) { 6635 builder.append("src: "); 6636 builder.append(srcArgs.getCodePath()); 6637 } 6638 if (targetArgs != null) { 6639 builder.append(" target : "); 6640 builder.append(targetArgs.getCodePath()); 6641 } 6642 Log.i(TAG, builder.toString()); 6643 } 6644 } 6645 6646 @Override 6647 void handleReturnCode() { 6648 targetArgs.doPostInstall(mRet, uid); 6649 int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 6650 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 6651 currentStatus = PackageManager.MOVE_SUCCEEDED; 6652 } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){ 6653 currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 6654 } 6655 processPendingMove(this, currentStatus); 6656 } 6657 6658 @Override 6659 void handleServiceError() { 6660 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6661 } 6662 } 6663 6664 /** 6665 * Used during creation of InstallArgs 6666 * 6667 * @param flags package installation flags 6668 * @return true if should be installed on external storage 6669 */ 6670 private static boolean installOnSd(int flags) { 6671 if ((flags & PackageManager.INSTALL_INTERNAL) != 0) { 6672 return false; 6673 } 6674 if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) { 6675 return true; 6676 } 6677 return false; 6678 } 6679 6680 /** 6681 * Used during creation of InstallArgs 6682 * 6683 * @param flags package installation flags 6684 * @return true if should be installed as forward locked 6685 */ 6686 private static boolean installForwardLocked(int flags) { 6687 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6688 } 6689 6690 private InstallArgs createInstallArgs(InstallParams params) { 6691 if (installOnSd(params.flags) || params.isForwardLocked()) { 6692 return new AsecInstallArgs(params); 6693 } else { 6694 return new FileInstallArgs(params); 6695 } 6696 } 6697 6698 private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath, 6699 String nativeLibraryPath) { 6700 final boolean isInAsec; 6701 if (installOnSd(flags)) { 6702 /* Apps on SD card are always in ASEC containers. */ 6703 isInAsec = true; 6704 } else if (installForwardLocked(flags) 6705 && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 6706 /* 6707 * Forward-locked apps are only in ASEC containers if they're the 6708 * new style 6709 */ 6710 isInAsec = true; 6711 } else { 6712 isInAsec = false; 6713 } 6714 6715 if (isInAsec) { 6716 return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath, 6717 installOnSd(flags), installForwardLocked(flags)); 6718 } else { 6719 return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath); 6720 } 6721 } 6722 6723 // Used by package mover 6724 private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir) { 6725 if (installOnSd(flags) || installForwardLocked(flags)) { 6726 String cid = getNextCodePath(packageURI.getPath(), pkgName, "/" 6727 + AsecInstallArgs.RES_FILE_NAME); 6728 return new AsecInstallArgs(packageURI, cid, installOnSd(flags), 6729 installForwardLocked(flags)); 6730 } else { 6731 return new FileInstallArgs(packageURI, pkgName, dataDir); 6732 } 6733 } 6734 6735 static abstract class InstallArgs { 6736 final IPackageInstallObserver observer; 6737 // Always refers to PackageManager flags only 6738 final int flags; 6739 final Uri packageURI; 6740 final String installerPackageName; 6741 final ManifestDigest manifestDigest; 6742 final UserHandle user; 6743 6744 InstallArgs(Uri packageURI, IPackageInstallObserver observer, int flags, 6745 String installerPackageName, ManifestDigest manifestDigest, 6746 UserHandle user) { 6747 this.packageURI = packageURI; 6748 this.flags = flags; 6749 this.observer = observer; 6750 this.installerPackageName = installerPackageName; 6751 this.manifestDigest = manifestDigest; 6752 this.user = user; 6753 } 6754 6755 abstract void createCopyFile(); 6756 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 6757 abstract int doPreInstall(int status); 6758 abstract boolean doRename(int status, String pkgName, String oldCodePath); 6759 6760 abstract int doPostInstall(int status, int uid); 6761 abstract String getCodePath(); 6762 abstract String getResourcePath(); 6763 abstract String getNativeLibraryPath(); 6764 // Need installer lock especially for dex file removal. 6765 abstract void cleanUpResourcesLI(); 6766 abstract boolean doPostDeleteLI(boolean delete); 6767 abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException; 6768 6769 /** 6770 * Called before the source arguments are copied. This is used mostly 6771 * for MoveParams when it needs to read the source file to put it in the 6772 * destination. 6773 */ 6774 int doPreCopy() { 6775 return PackageManager.INSTALL_SUCCEEDED; 6776 } 6777 6778 /** 6779 * Called after the source arguments are copied. This is used mostly for 6780 * MoveParams when it needs to read the source file to put it in the 6781 * destination. 6782 * 6783 * @return 6784 */ 6785 int doPostCopy(int uid) { 6786 return PackageManager.INSTALL_SUCCEEDED; 6787 } 6788 6789 protected boolean isFwdLocked() { 6790 return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 6791 } 6792 6793 UserHandle getUser() { 6794 return user; 6795 } 6796 } 6797 6798 class FileInstallArgs extends InstallArgs { 6799 File installDir; 6800 String codeFileName; 6801 String resourceFileName; 6802 String libraryPath; 6803 boolean created = false; 6804 6805 FileInstallArgs(InstallParams params) { 6806 super(params.getPackageUri(), params.observer, params.flags, 6807 params.installerPackageName, params.getManifestDigest(), 6808 params.getUser()); 6809 } 6810 6811 FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath) { 6812 super(null, null, 0, null, null, null); 6813 File codeFile = new File(fullCodePath); 6814 installDir = codeFile.getParentFile(); 6815 codeFileName = fullCodePath; 6816 resourceFileName = fullResourcePath; 6817 libraryPath = nativeLibraryPath; 6818 } 6819 6820 FileInstallArgs(Uri packageURI, String pkgName, String dataDir) { 6821 super(packageURI, null, 0, null, null, null); 6822 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 6823 String apkName = getNextCodePath(null, pkgName, ".apk"); 6824 codeFileName = new File(installDir, apkName + ".apk").getPath(); 6825 resourceFileName = getResourcePathFromCodePath(); 6826 libraryPath = new File(mAppLibInstallDir, pkgName).getPath(); 6827 } 6828 6829 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 6830 final long lowThreshold; 6831 6832 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 6833 .getService(DeviceStorageMonitorService.SERVICE); 6834 if (dsm == null) { 6835 Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed"); 6836 lowThreshold = 0L; 6837 } else { 6838 if (dsm.isMemoryLow()) { 6839 Log.w(TAG, "Memory is reported as being too low; aborting package install"); 6840 return false; 6841 } 6842 6843 lowThreshold = dsm.getMemoryLowThreshold(); 6844 } 6845 6846 try { 6847 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6848 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6849 return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold); 6850 } finally { 6851 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6852 } 6853 } 6854 6855 String getCodePath() { 6856 return codeFileName; 6857 } 6858 6859 void createCopyFile() { 6860 installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir; 6861 codeFileName = createTempPackageFile(installDir).getPath(); 6862 resourceFileName = getResourcePathFromCodePath(); 6863 libraryPath = getLibraryPathFromCodePath(); 6864 created = true; 6865 } 6866 6867 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 6868 if (temp) { 6869 // Generate temp file name 6870 createCopyFile(); 6871 } 6872 // Get a ParcelFileDescriptor to write to the output file 6873 File codeFile = new File(codeFileName); 6874 if (!created) { 6875 try { 6876 codeFile.createNewFile(); 6877 // Set permissions 6878 if (!setPermissions()) { 6879 // Failed setting permissions. 6880 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6881 } 6882 } catch (IOException e) { 6883 Slog.w(TAG, "Failed to create file " + codeFile); 6884 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6885 } 6886 } 6887 ParcelFileDescriptor out = null; 6888 try { 6889 out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE); 6890 } catch (FileNotFoundException e) { 6891 Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName); 6892 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6893 } 6894 // Copy the resource now 6895 int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6896 try { 6897 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 6898 Intent.FLAG_GRANT_READ_URI_PERMISSION); 6899 ret = imcs.copyResource(packageURI, null, out); 6900 } finally { 6901 IoUtils.closeQuietly(out); 6902 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 6903 } 6904 6905 if (isFwdLocked()) { 6906 final File destResourceFile = new File(getResourcePath()); 6907 6908 // Copy the public files 6909 try { 6910 PackageHelper.extractPublicFiles(codeFileName, destResourceFile); 6911 } catch (IOException e) { 6912 Slog.e(TAG, "Couldn't create a new zip file for the public parts of a" 6913 + " forward-locked app."); 6914 destResourceFile.delete(); 6915 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 6916 } 6917 } 6918 6919 final File nativeLibraryFile = new File(getNativeLibraryPath()); 6920 Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath()); 6921 if (nativeLibraryFile.exists()) { 6922 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 6923 nativeLibraryFile.delete(); 6924 } 6925 try { 6926 int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile); 6927 if (copyRet != PackageManager.INSTALL_SUCCEEDED) { 6928 return copyRet; 6929 } 6930 } catch (IOException e) { 6931 Slog.e(TAG, "Copying native libraries failed", e); 6932 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 6933 } 6934 6935 return ret; 6936 } 6937 6938 int doPreInstall(int status) { 6939 if (status != PackageManager.INSTALL_SUCCEEDED) { 6940 cleanUp(); 6941 } 6942 return status; 6943 } 6944 6945 boolean doRename(int status, final String pkgName, String oldCodePath) { 6946 if (status != PackageManager.INSTALL_SUCCEEDED) { 6947 cleanUp(); 6948 return false; 6949 } else { 6950 final File oldCodeFile = new File(getCodePath()); 6951 final File oldResourceFile = new File(getResourcePath()); 6952 final File oldLibraryFile = new File(getNativeLibraryPath()); 6953 6954 // Rename APK file based on packageName 6955 final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk"); 6956 final File newCodeFile = new File(installDir, apkName + ".apk"); 6957 if (!oldCodeFile.renameTo(newCodeFile)) { 6958 return false; 6959 } 6960 codeFileName = newCodeFile.getPath(); 6961 6962 // Rename public resource file if it's forward-locked. 6963 final File newResFile = new File(getResourcePathFromCodePath()); 6964 if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) { 6965 return false; 6966 } 6967 resourceFileName = newResFile.getPath(); 6968 6969 // Rename library path 6970 final File newLibraryFile = new File(getLibraryPathFromCodePath()); 6971 if (newLibraryFile.exists()) { 6972 NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile); 6973 newLibraryFile.delete(); 6974 } 6975 if (!oldLibraryFile.renameTo(newLibraryFile)) { 6976 Slog.e(TAG, "Cannot rename native library directory " 6977 + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath()); 6978 return false; 6979 } 6980 libraryPath = newLibraryFile.getPath(); 6981 6982 // Attempt to set permissions 6983 if (!setPermissions()) { 6984 return false; 6985 } 6986 6987 if (!SELinux.restorecon(newCodeFile)) { 6988 return false; 6989 } 6990 6991 return true; 6992 } 6993 } 6994 6995 int doPostInstall(int status, int uid) { 6996 if (status != PackageManager.INSTALL_SUCCEEDED) { 6997 cleanUp(); 6998 } 6999 return status; 7000 } 7001 7002 String getResourcePath() { 7003 return resourceFileName; 7004 } 7005 7006 private String getResourcePathFromCodePath() { 7007 final String codePath = getCodePath(); 7008 if (isFwdLocked()) { 7009 final StringBuilder sb = new StringBuilder(); 7010 7011 sb.append(mAppInstallDir.getPath()); 7012 sb.append('/'); 7013 sb.append(getApkName(codePath)); 7014 sb.append(".zip"); 7015 7016 /* 7017 * If our APK is a temporary file, mark the resource as a 7018 * temporary file as well so it can be cleaned up after 7019 * catastrophic failure. 7020 */ 7021 if (codePath.endsWith(".tmp")) { 7022 sb.append(".tmp"); 7023 } 7024 7025 return sb.toString(); 7026 } else { 7027 return codePath; 7028 } 7029 } 7030 7031 private String getLibraryPathFromCodePath() { 7032 return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath(); 7033 } 7034 7035 @Override 7036 String getNativeLibraryPath() { 7037 if (libraryPath == null) { 7038 libraryPath = getLibraryPathFromCodePath(); 7039 } 7040 return libraryPath; 7041 } 7042 7043 private boolean cleanUp() { 7044 boolean ret = true; 7045 String sourceDir = getCodePath(); 7046 String publicSourceDir = getResourcePath(); 7047 if (sourceDir != null) { 7048 File sourceFile = new File(sourceDir); 7049 if (!sourceFile.exists()) { 7050 Slog.w(TAG, "Package source " + sourceDir + " does not exist."); 7051 ret = false; 7052 } 7053 // Delete application's code and resources 7054 sourceFile.delete(); 7055 } 7056 if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) { 7057 final File publicSourceFile = new File(publicSourceDir); 7058 if (!publicSourceFile.exists()) { 7059 Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist."); 7060 } 7061 if (publicSourceFile.exists()) { 7062 publicSourceFile.delete(); 7063 } 7064 } 7065 7066 if (libraryPath != null) { 7067 File nativeLibraryFile = new File(libraryPath); 7068 NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile); 7069 if (!nativeLibraryFile.delete()) { 7070 Slog.w(TAG, "Couldn't delete native library directory " + libraryPath); 7071 } 7072 } 7073 7074 return ret; 7075 } 7076 7077 void cleanUpResourcesLI() { 7078 String sourceDir = getCodePath(); 7079 if (cleanUp()) { 7080 int retCode = mInstaller.rmdex(sourceDir); 7081 if (retCode < 0) { 7082 Slog.w(TAG, "Couldn't remove dex file for package: " 7083 + " at location " 7084 + sourceDir + ", retcode=" + retCode); 7085 // we don't consider this to be a failure of the core package deletion 7086 } 7087 } 7088 } 7089 7090 private boolean setPermissions() { 7091 // TODO Do this in a more elegant way later on. for now just a hack 7092 if (!isFwdLocked()) { 7093 final int filePermissions = 7094 FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP 7095 |FileUtils.S_IROTH; 7096 int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1); 7097 if (retCode != 0) { 7098 Slog.e(TAG, "Couldn't set new package file permissions for " + 7099 getCodePath() 7100 + ". The return code was: " + retCode); 7101 // TODO Define new internal error 7102 return false; 7103 } 7104 return true; 7105 } 7106 return true; 7107 } 7108 7109 boolean doPostDeleteLI(boolean delete) { 7110 // XXX err, shouldn't we respect the delete flag? 7111 cleanUpResourcesLI(); 7112 return true; 7113 } 7114 } 7115 7116 private boolean isAsecExternal(String cid) { 7117 final String asecPath = PackageHelper.getSdFilesystem(cid); 7118 return !asecPath.startsWith(mAsecInternalPath); 7119 } 7120 7121 /** 7122 * Extract the MountService "container ID" from the full code path of an 7123 * .apk. 7124 */ 7125 static String cidFromCodePath(String fullCodePath) { 7126 int eidx = fullCodePath.lastIndexOf("/"); 7127 String subStr1 = fullCodePath.substring(0, eidx); 7128 int sidx = subStr1.lastIndexOf("/"); 7129 return subStr1.substring(sidx+1, eidx); 7130 } 7131 7132 class AsecInstallArgs extends InstallArgs { 7133 static final String RES_FILE_NAME = "pkg.apk"; 7134 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 7135 7136 String cid; 7137 String packagePath; 7138 String resourcePath; 7139 String libraryPath; 7140 7141 AsecInstallArgs(InstallParams params) { 7142 super(params.getPackageUri(), params.observer, params.flags, 7143 params.installerPackageName, params.getManifestDigest(), 7144 params.getUser()); 7145 } 7146 7147 AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath, 7148 boolean isExternal, boolean isForwardLocked) { 7149 super(null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 7150 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 7151 null, null, null); 7152 // Extract cid from fullCodePath 7153 int eidx = fullCodePath.lastIndexOf("/"); 7154 String subStr1 = fullCodePath.substring(0, eidx); 7155 int sidx = subStr1.lastIndexOf("/"); 7156 cid = subStr1.substring(sidx+1, eidx); 7157 setCachePath(subStr1); 7158 } 7159 7160 AsecInstallArgs(String cid, boolean isForwardLocked) { 7161 super(null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0) 7162 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 7163 null, null, null); 7164 this.cid = cid; 7165 setCachePath(PackageHelper.getSdDir(cid)); 7166 } 7167 7168 AsecInstallArgs(Uri packageURI, String cid, boolean isExternal, boolean isForwardLocked) { 7169 super(packageURI, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0) 7170 | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0), 7171 null, null, null); 7172 this.cid = cid; 7173 } 7174 7175 void createCopyFile() { 7176 cid = getTempContainerId(); 7177 } 7178 7179 boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException { 7180 try { 7181 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 7182 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7183 return imcs.checkExternalFreeStorage(packageURI, isFwdLocked()); 7184 } finally { 7185 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 7186 } 7187 } 7188 7189 private final boolean isExternal() { 7190 return (flags & PackageManager.INSTALL_EXTERNAL) != 0; 7191 } 7192 7193 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 7194 if (temp) { 7195 createCopyFile(); 7196 } else { 7197 /* 7198 * Pre-emptively destroy the container since it's destroyed if 7199 * copying fails due to it existing anyway. 7200 */ 7201 PackageHelper.destroySdDir(cid); 7202 } 7203 7204 final String newCachePath; 7205 try { 7206 mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI, 7207 Intent.FLAG_GRANT_READ_URI_PERMISSION); 7208 newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(), 7209 RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked()); 7210 } finally { 7211 mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION); 7212 } 7213 7214 if (newCachePath != null) { 7215 setCachePath(newCachePath); 7216 return PackageManager.INSTALL_SUCCEEDED; 7217 } else { 7218 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7219 } 7220 } 7221 7222 @Override 7223 String getCodePath() { 7224 return packagePath; 7225 } 7226 7227 @Override 7228 String getResourcePath() { 7229 return resourcePath; 7230 } 7231 7232 @Override 7233 String getNativeLibraryPath() { 7234 return libraryPath; 7235 } 7236 7237 int doPreInstall(int status) { 7238 if (status != PackageManager.INSTALL_SUCCEEDED) { 7239 // Destroy container 7240 PackageHelper.destroySdDir(cid); 7241 } else { 7242 boolean mounted = PackageHelper.isContainerMounted(cid); 7243 if (!mounted) { 7244 String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(), 7245 Process.SYSTEM_UID); 7246 if (newCachePath != null) { 7247 setCachePath(newCachePath); 7248 } else { 7249 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7250 } 7251 } 7252 } 7253 return status; 7254 } 7255 7256 boolean doRename(int status, final String pkgName, 7257 String oldCodePath) { 7258 String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME); 7259 String newCachePath = null; 7260 if (PackageHelper.isContainerMounted(cid)) { 7261 // Unmount the container 7262 if (!PackageHelper.unMountSdDir(cid)) { 7263 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 7264 return false; 7265 } 7266 } 7267 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 7268 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 7269 " which might be stale. Will try to clean up."); 7270 // Clean up the stale container and proceed to recreate. 7271 if (!PackageHelper.destroySdDir(newCacheId)) { 7272 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 7273 return false; 7274 } 7275 // Successfully cleaned up stale container. Try to rename again. 7276 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 7277 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 7278 + " inspite of cleaning it up."); 7279 return false; 7280 } 7281 } 7282 if (!PackageHelper.isContainerMounted(newCacheId)) { 7283 Slog.w(TAG, "Mounting container " + newCacheId); 7284 newCachePath = PackageHelper.mountSdDir(newCacheId, 7285 getEncryptKey(), Process.SYSTEM_UID); 7286 } else { 7287 newCachePath = PackageHelper.getSdDir(newCacheId); 7288 } 7289 if (newCachePath == null) { 7290 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 7291 return false; 7292 } 7293 Log.i(TAG, "Succesfully renamed " + cid + 7294 " to " + newCacheId + 7295 " at new path: " + newCachePath); 7296 cid = newCacheId; 7297 setCachePath(newCachePath); 7298 return true; 7299 } 7300 7301 private void setCachePath(String newCachePath) { 7302 File cachePath = new File(newCachePath); 7303 libraryPath = new File(cachePath, LIB_DIR_NAME).getPath(); 7304 packagePath = new File(cachePath, RES_FILE_NAME).getPath(); 7305 7306 if (isFwdLocked()) { 7307 resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath(); 7308 } else { 7309 resourcePath = packagePath; 7310 } 7311 } 7312 7313 int doPostInstall(int status, int uid) { 7314 if (status != PackageManager.INSTALL_SUCCEEDED) { 7315 cleanUp(); 7316 } else { 7317 final int groupOwner; 7318 final String protectedFile; 7319 if (isFwdLocked()) { 7320 groupOwner = UserHandle.getSharedAppGid(uid); 7321 protectedFile = RES_FILE_NAME; 7322 } else { 7323 groupOwner = -1; 7324 protectedFile = null; 7325 } 7326 7327 if (uid < Process.FIRST_APPLICATION_UID 7328 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 7329 Slog.e(TAG, "Failed to finalize " + cid); 7330 PackageHelper.destroySdDir(cid); 7331 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7332 } 7333 7334 boolean mounted = PackageHelper.isContainerMounted(cid); 7335 if (!mounted) { 7336 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 7337 } 7338 } 7339 return status; 7340 } 7341 7342 private void cleanUp() { 7343 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 7344 7345 // Destroy secure container 7346 PackageHelper.destroySdDir(cid); 7347 } 7348 7349 void cleanUpResourcesLI() { 7350 String sourceFile = getCodePath(); 7351 // Remove dex file 7352 int retCode = mInstaller.rmdex(sourceFile); 7353 if (retCode < 0) { 7354 Slog.w(TAG, "Couldn't remove dex file for package: " 7355 + " at location " 7356 + sourceFile.toString() + ", retcode=" + retCode); 7357 // we don't consider this to be a failure of the core package deletion 7358 } 7359 cleanUp(); 7360 } 7361 7362 boolean matchContainer(String app) { 7363 if (cid.startsWith(app)) { 7364 return true; 7365 } 7366 return false; 7367 } 7368 7369 String getPackageName() { 7370 return getAsecPackageName(cid); 7371 } 7372 7373 boolean doPostDeleteLI(boolean delete) { 7374 boolean ret = false; 7375 boolean mounted = PackageHelper.isContainerMounted(cid); 7376 if (mounted) { 7377 // Unmount first 7378 ret = PackageHelper.unMountSdDir(cid); 7379 } 7380 if (ret && delete) { 7381 cleanUpResourcesLI(); 7382 } 7383 return ret; 7384 } 7385 7386 @Override 7387 int doPreCopy() { 7388 if (isFwdLocked()) { 7389 if (!PackageHelper.fixSdPermissions(cid, 7390 getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) { 7391 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7392 } 7393 } 7394 7395 return PackageManager.INSTALL_SUCCEEDED; 7396 } 7397 7398 @Override 7399 int doPostCopy(int uid) { 7400 if (isFwdLocked()) { 7401 if (uid < Process.FIRST_APPLICATION_UID 7402 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 7403 RES_FILE_NAME)) { 7404 Slog.e(TAG, "Failed to finalize " + cid); 7405 PackageHelper.destroySdDir(cid); 7406 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 7407 } 7408 } 7409 7410 return PackageManager.INSTALL_SUCCEEDED; 7411 } 7412 }; 7413 7414 static String getAsecPackageName(String packageCid) { 7415 int idx = packageCid.lastIndexOf("-"); 7416 if (idx == -1) { 7417 return packageCid; 7418 } 7419 return packageCid.substring(0, idx); 7420 } 7421 7422 // Utility method used to create code paths based on package name and available index. 7423 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 7424 String idxStr = ""; 7425 int idx = 1; 7426 // Fall back to default value of idx=1 if prefix is not 7427 // part of oldCodePath 7428 if (oldCodePath != null) { 7429 String subStr = oldCodePath; 7430 // Drop the suffix right away 7431 if (subStr.endsWith(suffix)) { 7432 subStr = subStr.substring(0, subStr.length() - suffix.length()); 7433 } 7434 // If oldCodePath already contains prefix find out the 7435 // ending index to either increment or decrement. 7436 int sidx = subStr.lastIndexOf(prefix); 7437 if (sidx != -1) { 7438 subStr = subStr.substring(sidx + prefix.length()); 7439 if (subStr != null) { 7440 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 7441 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 7442 } 7443 try { 7444 idx = Integer.parseInt(subStr); 7445 if (idx <= 1) { 7446 idx++; 7447 } else { 7448 idx--; 7449 } 7450 } catch(NumberFormatException e) { 7451 } 7452 } 7453 } 7454 } 7455 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 7456 return prefix + idxStr; 7457 } 7458 7459 // Utility method used to ignore ADD/REMOVE events 7460 // by directory observer. 7461 private static boolean ignoreCodePath(String fullPathStr) { 7462 String apkName = getApkName(fullPathStr); 7463 int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX); 7464 if (idx != -1 && ((idx+1) < apkName.length())) { 7465 // Make sure the package ends with a numeral 7466 String version = apkName.substring(idx+1); 7467 try { 7468 Integer.parseInt(version); 7469 return true; 7470 } catch (NumberFormatException e) {} 7471 } 7472 return false; 7473 } 7474 7475 // Utility method that returns the relative package path with respect 7476 // to the installation directory. Like say for /data/data/com.test-1.apk 7477 // string com.test-1 is returned. 7478 static String getApkName(String codePath) { 7479 if (codePath == null) { 7480 return null; 7481 } 7482 int sidx = codePath.lastIndexOf("/"); 7483 int eidx = codePath.lastIndexOf("."); 7484 if (eidx == -1) { 7485 eidx = codePath.length(); 7486 } else if (eidx == 0) { 7487 Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name"); 7488 return null; 7489 } 7490 return codePath.substring(sidx+1, eidx); 7491 } 7492 7493 class PackageInstalledInfo { 7494 String name; 7495 int uid; 7496 // The set of users that originally had this package installed. 7497 int[] origUsers; 7498 // The set of users that now have this package installed. 7499 int[] newUsers; 7500 PackageParser.Package pkg; 7501 int returnCode; 7502 PackageRemovedInfo removedInfo; 7503 } 7504 7505 /* 7506 * Install a non-existing package. 7507 */ 7508 private void installNewPackageLI(PackageParser.Package pkg, 7509 int parseFlags, int scanMode, UserHandle user, 7510 String installerPackageName, PackageInstalledInfo res) { 7511 // Remember this for later, in case we need to rollback this install 7512 String pkgName = pkg.packageName; 7513 7514 boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists(); 7515 synchronized(mPackages) { 7516 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 7517 // A package with the same name is already installed, though 7518 // it has been renamed to an older name. The package we 7519 // are trying to install should be installed as an update to 7520 // the existing one, but that has not been requested, so bail. 7521 Slog.w(TAG, "Attempt to re-install " + pkgName 7522 + " without first uninstalling package running as " 7523 + mSettings.mRenamedPackages.get(pkgName)); 7524 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7525 return; 7526 } 7527 if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) { 7528 // Don't allow installation over an existing package with the same name. 7529 Slog.w(TAG, "Attempt to re-install " + pkgName 7530 + " without first uninstalling."); 7531 res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 7532 return; 7533 } 7534 } 7535 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7536 PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode, 7537 System.currentTimeMillis(), user); 7538 if (newPackage == null) { 7539 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7540 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7541 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7542 } 7543 } else { 7544 updateSettingsLI(newPackage, 7545 installerPackageName, 7546 res); 7547 // delete the partially installed application. the data directory will have to be 7548 // restored if it was already existing 7549 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7550 // remove package from internal structures. Note that we want deletePackageX to 7551 // delete the package data and cache directories that it created in 7552 // scanPackageLocked, unless those directories existed before we even tried to 7553 // install. 7554 deletePackageLI(pkgName, UserHandle.ALL, false, 7555 dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0, 7556 res.removedInfo, true); 7557 } 7558 } 7559 } 7560 7561 private void replacePackageLI(PackageParser.Package pkg, 7562 int parseFlags, int scanMode, UserHandle user, 7563 String installerPackageName, PackageInstalledInfo res) { 7564 7565 PackageParser.Package oldPackage; 7566 String pkgName = pkg.packageName; 7567 // First find the old package info and check signatures 7568 synchronized(mPackages) { 7569 oldPackage = mPackages.get(pkgName); 7570 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 7571 != PackageManager.SIGNATURE_MATCH) { 7572 Slog.w(TAG, "New package has a different signature: " + pkgName); 7573 res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 7574 return; 7575 } 7576 } 7577 boolean sysPkg = (isSystemApp(oldPackage)); 7578 if (sysPkg) { 7579 replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 7580 user, installerPackageName, res); 7581 } else { 7582 replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode, 7583 user, installerPackageName, res); 7584 } 7585 } 7586 7587 private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage, 7588 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 7589 String installerPackageName, PackageInstalledInfo res) { 7590 PackageParser.Package newPackage = null; 7591 String pkgName = deletedPackage.packageName; 7592 boolean deletedPkg = true; 7593 boolean updatedSettings = false; 7594 7595 long origUpdateTime; 7596 if (pkg.mExtras != null) { 7597 origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime; 7598 } else { 7599 origUpdateTime = 0; 7600 } 7601 7602 // First delete the existing package while retaining the data directory 7603 if (!deletePackageLI(pkgName, null, true, PackageManager.DELETE_KEEP_DATA, 7604 res.removedInfo, true)) { 7605 // If the existing package wasn't successfully deleted 7606 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 7607 deletedPkg = false; 7608 } else { 7609 // Successfully deleted the old package. Now proceed with re-installation 7610 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7611 newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME, 7612 System.currentTimeMillis(), user); 7613 if (newPackage == null) { 7614 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7615 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7616 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7617 } 7618 } else { 7619 updateSettingsLI(newPackage, 7620 installerPackageName, 7621 res); 7622 updatedSettings = true; 7623 } 7624 } 7625 7626 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7627 // remove package from internal structures. Note that we want deletePackageX to 7628 // delete the package data and cache directories that it created in 7629 // scanPackageLocked, unless those directories existed before we even tried to 7630 // install. 7631 if(updatedSettings) { 7632 deletePackageLI( 7633 pkgName, null, true, 7634 PackageManager.DELETE_KEEP_DATA, 7635 res.removedInfo, true); 7636 } 7637 // Since we failed to install the new package we need to restore the old 7638 // package that we deleted. 7639 if(deletedPkg) { 7640 File restoreFile = new File(deletedPackage.mPath); 7641 // Parse old package 7642 boolean oldOnSd = isExternal(deletedPackage); 7643 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 7644 (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) | 7645 (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0); 7646 int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE 7647 | SCAN_UPDATE_TIME; 7648 if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode, 7649 origUpdateTime, null) == null) { 7650 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade"); 7651 return; 7652 } 7653 // Restore of old package succeeded. Update permissions. 7654 // writer 7655 synchronized (mPackages) { 7656 updatePermissionsLPw(deletedPackage.packageName, deletedPackage, 7657 UPDATE_PERMISSIONS_ALL); 7658 // can downgrade to reader 7659 mSettings.writeLPr(); 7660 } 7661 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 7662 } 7663 } 7664 } 7665 7666 private void replaceSystemPackageLI(PackageParser.Package deletedPackage, 7667 PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user, 7668 String installerPackageName, PackageInstalledInfo res) { 7669 PackageParser.Package newPackage = null; 7670 boolean updatedSettings = false; 7671 parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING | 7672 PackageParser.PARSE_IS_SYSTEM; 7673 String packageName = deletedPackage.packageName; 7674 res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 7675 if (packageName == null) { 7676 Slog.w(TAG, "Attempt to delete null packageName."); 7677 return; 7678 } 7679 PackageParser.Package oldPkg; 7680 PackageSetting oldPkgSetting; 7681 // reader 7682 synchronized (mPackages) { 7683 oldPkg = mPackages.get(packageName); 7684 oldPkgSetting = mSettings.mPackages.get(packageName); 7685 if((oldPkg == null) || (oldPkg.applicationInfo == null) || 7686 (oldPkgSetting == null)) { 7687 Slog.w(TAG, "Couldn't find package:"+packageName+" information"); 7688 return; 7689 } 7690 } 7691 7692 killApplication(packageName, oldPkg.applicationInfo.uid); 7693 7694 res.removedInfo.uid = oldPkg.applicationInfo.uid; 7695 res.removedInfo.removedPackage = packageName; 7696 // Remove existing system package 7697 removePackageLI(oldPkgSetting, true); 7698 // writer 7699 synchronized (mPackages) { 7700 if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) { 7701 // We didn't need to disable the .apk as a current system package, 7702 // which means we are replacing another update that is already 7703 // installed. We need to make sure to delete the older one's .apk. 7704 res.removedInfo.args = createInstallArgs(0, 7705 deletedPackage.applicationInfo.sourceDir, 7706 deletedPackage.applicationInfo.publicSourceDir, 7707 deletedPackage.applicationInfo.nativeLibraryDir); 7708 } else { 7709 res.removedInfo.args = null; 7710 } 7711 } 7712 7713 // Successfully disabled the old package. Now proceed with re-installation 7714 mLastScanError = PackageManager.INSTALL_SUCCEEDED; 7715 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7716 newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user); 7717 if (newPackage == null) { 7718 Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath); 7719 if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) { 7720 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK; 7721 } 7722 } else { 7723 if (newPackage.mExtras != null) { 7724 final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras; 7725 newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime; 7726 newPkgSetting.lastUpdateTime = System.currentTimeMillis(); 7727 } 7728 updateSettingsLI(newPackage, installerPackageName, res); 7729 updatedSettings = true; 7730 } 7731 7732 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 7733 // Re installation failed. Restore old information 7734 // Remove new pkg information 7735 if (newPackage != null) { 7736 removeInstalledPackageLI(newPackage, true); 7737 } 7738 // Add back the old system package 7739 scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user); 7740 // Restore the old system information in Settings 7741 synchronized(mPackages) { 7742 if (updatedSettings) { 7743 mSettings.enableSystemPackageLPw(packageName); 7744 mSettings.setInstallerPackageName(packageName, 7745 oldPkgSetting.installerPackageName); 7746 } 7747 mSettings.writeLPr(); 7748 } 7749 } 7750 } 7751 7752 // Utility method used to move dex files during install. 7753 private int moveDexFilesLI(PackageParser.Package newPackage) { 7754 int retCode; 7755 if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) { 7756 retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath); 7757 if (retCode != 0) { 7758 if (mNoDexOpt) { 7759 /* 7760 * If we're in an engineering build, programs are lazily run 7761 * through dexopt. If the .dex file doesn't exist yet, it 7762 * will be created when the program is run next. 7763 */ 7764 Slog.i(TAG, "dex file doesn't exist, skipping move: " + newPackage.mPath); 7765 } else { 7766 Slog.e(TAG, "Couldn't rename dex file: " + newPackage.mPath); 7767 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7768 } 7769 } 7770 } 7771 return PackageManager.INSTALL_SUCCEEDED; 7772 } 7773 7774 private void updateSettingsLI(PackageParser.Package newPackage, 7775 String installerPackageName, PackageInstalledInfo res) { 7776 String pkgName = newPackage.packageName; 7777 synchronized (mPackages) { 7778 //write settings. the installStatus will be incomplete at this stage. 7779 //note that the new package setting would have already been 7780 //added to mPackages. It hasn't been persisted yet. 7781 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 7782 mSettings.writeLPr(); 7783 } 7784 7785 if ((res.returnCode = moveDexFilesLI(newPackage)) 7786 != PackageManager.INSTALL_SUCCEEDED) { 7787 // Discontinue if moving dex files failed. 7788 return; 7789 } 7790 7791 Log.d(TAG, "New package installed in " + newPackage.mPath); 7792 7793 synchronized (mPackages) { 7794 updatePermissionsLPw(newPackage.packageName, newPackage, 7795 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 7796 ? UPDATE_PERMISSIONS_ALL : 0)); 7797 res.name = pkgName; 7798 res.uid = newPackage.applicationInfo.uid; 7799 res.pkg = newPackage; 7800 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 7801 mSettings.setInstallerPackageName(pkgName, installerPackageName); 7802 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 7803 //to update install status 7804 mSettings.writeLPr(); 7805 } 7806 } 7807 7808 private void installPackageLI(InstallArgs args, 7809 boolean newInstall, PackageInstalledInfo res) { 7810 int pFlags = args.flags; 7811 String installerPackageName = args.installerPackageName; 7812 File tmpPackageFile = new File(args.getCodePath()); 7813 boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 7814 boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0); 7815 boolean replace = false; 7816 int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE 7817 | (newInstall ? SCAN_NEW_INSTALL : 0); 7818 // Result object to be returned 7819 res.returnCode = PackageManager.INSTALL_SUCCEEDED; 7820 7821 // Retrieve PackageSettings and parse package 7822 int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 7823 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 7824 | (onSd ? PackageParser.PARSE_ON_SDCARD : 0); 7825 PackageParser pp = new PackageParser(tmpPackageFile.getPath()); 7826 pp.setSeparateProcesses(mSeparateProcesses); 7827 final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile, 7828 null, mMetrics, parseFlags); 7829 if (pkg == null) { 7830 res.returnCode = pp.getParseError(); 7831 return; 7832 } 7833 String pkgName = res.name = pkg.packageName; 7834 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 7835 if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) { 7836 res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY; 7837 return; 7838 } 7839 } 7840 if (GET_CERTIFICATES && !pp.collectCertificates(pkg, parseFlags)) { 7841 res.returnCode = pp.getParseError(); 7842 return; 7843 } 7844 7845 /* If the installer passed in a manifest digest, compare it now. */ 7846 if (args.manifestDigest != null) { 7847 if (DEBUG_INSTALL) { 7848 final String parsedManifest = pkg.manifestDigest == null ? "null" 7849 : pkg.manifestDigest.toString(); 7850 Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. " 7851 + parsedManifest); 7852 } 7853 7854 if (!args.manifestDigest.equals(pkg.manifestDigest)) { 7855 res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 7856 return; 7857 } 7858 } else if (DEBUG_INSTALL) { 7859 final String parsedManifest = pkg.manifestDigest == null 7860 ? "null" : pkg.manifestDigest.toString(); 7861 Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest); 7862 } 7863 7864 // Get rid of all references to package scan path via parser. 7865 pp = null; 7866 String oldCodePath = null; 7867 boolean systemApp = false; 7868 synchronized (mPackages) { 7869 // Check if installing already existing package 7870 if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 7871 String oldName = mSettings.mRenamedPackages.get(pkgName); 7872 if (pkg.mOriginalPackages != null 7873 && pkg.mOriginalPackages.contains(oldName) 7874 && mPackages.containsKey(oldName)) { 7875 // This package is derived from an original package, 7876 // and this device has been updating from that original 7877 // name. We must continue using the original name, so 7878 // rename the new package here. 7879 pkg.setPackageName(oldName); 7880 pkgName = pkg.packageName; 7881 replace = true; 7882 } else if (mPackages.containsKey(pkgName)) { 7883 // This package, under its official name, already exists 7884 // on the device; we should replace it. 7885 replace = true; 7886 } 7887 } 7888 PackageSetting ps = mSettings.mPackages.get(pkgName); 7889 if (ps != null) { 7890 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 7891 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 7892 systemApp = (ps.pkg.applicationInfo.flags & 7893 ApplicationInfo.FLAG_SYSTEM) != 0; 7894 } 7895 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7896 } 7897 } 7898 7899 if (systemApp && onSd) { 7900 // Disable updates to system apps on sdcard 7901 Slog.w(TAG, "Cannot install updates to system apps on sdcard"); 7902 res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 7903 return; 7904 } 7905 7906 if (!args.doRename(res.returnCode, pkgName, oldCodePath)) { 7907 res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 7908 return; 7909 } 7910 // Set application objects path explicitly after the rename 7911 setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath()); 7912 pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath(); 7913 if (replace) { 7914 replacePackageLI(pkg, parseFlags, scanMode, args.user, 7915 installerPackageName, res); 7916 } else { 7917 installNewPackageLI(pkg, parseFlags, scanMode, args.user, 7918 installerPackageName, res); 7919 } 7920 synchronized (mPackages) { 7921 final PackageSetting ps = mSettings.mPackages.get(pkgName); 7922 if (ps != null) { 7923 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 7924 } 7925 } 7926 } 7927 7928 private static boolean isForwardLocked(PackageParser.Package pkg) { 7929 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 7930 } 7931 7932 7933 private boolean isForwardLocked(PackageSetting ps) { 7934 return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0; 7935 } 7936 7937 private static boolean isExternal(PackageParser.Package pkg) { 7938 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 7939 } 7940 7941 private static boolean isExternal(PackageSetting ps) { 7942 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 7943 } 7944 7945 private static boolean isSystemApp(PackageParser.Package pkg) { 7946 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7947 } 7948 7949 private static boolean isSystemApp(ApplicationInfo info) { 7950 return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 7951 } 7952 7953 private static boolean isSystemApp(PackageSetting ps) { 7954 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 7955 } 7956 7957 private static boolean isUpdatedSystemApp(PackageParser.Package pkg) { 7958 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 7959 } 7960 7961 private int packageFlagsToInstallFlags(PackageSetting ps) { 7962 int installFlags = 0; 7963 if (isExternal(ps)) { 7964 installFlags |= PackageManager.INSTALL_EXTERNAL; 7965 } 7966 if (isForwardLocked(ps)) { 7967 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 7968 } 7969 return installFlags; 7970 } 7971 7972 private void deleteTempPackageFiles() { 7973 final FilenameFilter filter = new FilenameFilter() { 7974 public boolean accept(File dir, String name) { 7975 return name.startsWith("vmdl") && name.endsWith(".tmp"); 7976 } 7977 }; 7978 deleteTempPackageFilesInDirectory(mAppInstallDir, filter); 7979 deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter); 7980 } 7981 7982 private static final void deleteTempPackageFilesInDirectory(File directory, 7983 FilenameFilter filter) { 7984 final String[] tmpFilesList = directory.list(filter); 7985 if (tmpFilesList == null) { 7986 return; 7987 } 7988 for (int i = 0; i < tmpFilesList.length; i++) { 7989 final File tmpFile = new File(directory, tmpFilesList[i]); 7990 tmpFile.delete(); 7991 } 7992 } 7993 7994 private File createTempPackageFile(File installDir) { 7995 File tmpPackageFile; 7996 try { 7997 tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir); 7998 } catch (IOException e) { 7999 Slog.e(TAG, "Couldn't create temp file for downloaded package file."); 8000 return null; 8001 } 8002 try { 8003 FileUtils.setPermissions( 8004 tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR, 8005 -1, -1); 8006 if (!SELinux.restorecon(tmpPackageFile)) { 8007 return null; 8008 } 8009 } catch (IOException e) { 8010 Slog.e(TAG, "Trouble getting the canoncical path for a temp file."); 8011 return null; 8012 } 8013 return tmpPackageFile; 8014 } 8015 8016 public void deletePackage(final String packageName, 8017 final IPackageDeleteObserver observer, 8018 final int flags) { 8019 mContext.enforceCallingOrSelfPermission( 8020 android.Manifest.permission.DELETE_PACKAGES, null); 8021 // Queue up an async operation since the package deletion may take a little while. 8022 final int uid = Binder.getCallingUid(); 8023 mHandler.post(new Runnable() { 8024 public void run() { 8025 mHandler.removeCallbacks(this); 8026 final int returnCode = deletePackageX(packageName, uid, flags); 8027 if (observer != null) { 8028 try { 8029 observer.packageDeleted(packageName, returnCode); 8030 } catch (RemoteException e) { 8031 Log.i(TAG, "Observer no longer exists."); 8032 } //end catch 8033 } //end if 8034 } //end run 8035 }); 8036 } 8037 8038 /** 8039 * This method is an internal method that could be get invoked either 8040 * to delete an installed package or to clean up a failed installation. 8041 * After deleting an installed package, a broadcast is sent to notify any 8042 * listeners that the package has been installed. For cleaning up a failed 8043 * installation, the broadcast is not necessary since the package's 8044 * installation wouldn't have sent the initial broadcast either 8045 * The key steps in deleting a package are 8046 * deleting the package information in internal structures like mPackages, 8047 * deleting the packages base directories through installd 8048 * updating mSettings to reflect current status 8049 * persisting settings for later use 8050 * sending a broadcast if necessary 8051 */ 8052 private int deletePackageX(String packageName, int uid, int flags) { 8053 final PackageRemovedInfo info = new PackageRemovedInfo(); 8054 final boolean res; 8055 8056 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 8057 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 8058 try { 8059 if (dpm != null && dpm.packageHasActiveAdmins(packageName, UserHandle.getUserId(uid))) { 8060 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 8061 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 8062 } 8063 } catch (RemoteException e) { 8064 } 8065 8066 boolean removedForAllUsers = false; 8067 boolean systemUpdate = false; 8068 synchronized (mInstallLock) { 8069 res = deletePackageLI(packageName, 8070 (flags & PackageManager.DELETE_ALL_USERS) != 0 8071 ? UserHandle.ALL : new UserHandle(UserHandle.getUserId(uid)), 8072 true, flags | REMOVE_CHATTY, info, true); 8073 systemUpdate = info.isRemovedPackageSystemUpdate; 8074 if (res && !systemUpdate && mPackages.get(packageName) == null) { 8075 removedForAllUsers = true; 8076 } 8077 } 8078 8079 if (res) { 8080 info.sendBroadcast(true, systemUpdate, removedForAllUsers); 8081 8082 // If the removed package was a system update, the old system package 8083 // was re-enabled; we need to broadcast this information 8084 if (systemUpdate) { 8085 Bundle extras = new Bundle(1); 8086 extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0 8087 ? info.removedAppId : info.uid); 8088 extras.putBoolean(Intent.EXTRA_REPLACING, true); 8089 8090 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 8091 extras, null, null, null); 8092 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 8093 extras, null, null, null); 8094 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 8095 null, packageName, null, null); 8096 } 8097 } 8098 // Force a gc here. 8099 Runtime.getRuntime().gc(); 8100 // Delete the resources here after sending the broadcast to let 8101 // other processes clean up before deleting resources. 8102 if (info.args != null) { 8103 synchronized (mInstallLock) { 8104 info.args.doPostDeleteLI(true); 8105 } 8106 } 8107 8108 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 8109 } 8110 8111 static class PackageRemovedInfo { 8112 String removedPackage; 8113 int uid = -1; 8114 int removedAppId = -1; 8115 int[] removedUsers = null; 8116 boolean isRemovedPackageSystemUpdate = false; 8117 // Clean up resources deleted packages. 8118 InstallArgs args = null; 8119 8120 void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) { 8121 Bundle extras = new Bundle(1); 8122 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 8123 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove); 8124 if (replacing) { 8125 extras.putBoolean(Intent.EXTRA_REPLACING, true); 8126 } 8127 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 8128 if (removedPackage != null) { 8129 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 8130 extras, null, null, removedUsers); 8131 if (fullRemove && !replacing) { 8132 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage, 8133 extras, null, null, removedUsers); 8134 } 8135 } 8136 if (removedAppId >= 0) { 8137 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null, 8138 removedUsers); 8139 } 8140 } 8141 } 8142 8143 /* 8144 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 8145 * flag is not set, the data directory is removed as well. 8146 * make sure this flag is set for partially installed apps. If not its meaningless to 8147 * delete a partially installed application. 8148 */ 8149 private void removePackageDataLI(PackageSetting ps, PackageRemovedInfo outInfo, 8150 int flags, boolean writeSettings) { 8151 String packageName = ps.name; 8152 removePackageLI(ps, (flags&REMOVE_CHATTY) != 0); 8153 // Retrieve object to delete permissions for shared user later on 8154 final PackageSetting deletedPs; 8155 // reader 8156 synchronized (mPackages) { 8157 deletedPs = mSettings.mPackages.get(packageName); 8158 if (outInfo != null) { 8159 outInfo.removedPackage = packageName; 8160 outInfo.removedUsers = deletedPs != null 8161 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 8162 : null; 8163 } 8164 } 8165 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 8166 removeDataDirsLI(packageName); 8167 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 8168 } 8169 // writer 8170 synchronized (mPackages) { 8171 if (deletedPs != null) { 8172 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 8173 if (outInfo != null) { 8174 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 8175 } 8176 if (deletedPs != null) { 8177 updatePermissionsLPw(deletedPs.name, null, 0); 8178 if (deletedPs.sharedUser != null) { 8179 // remove permissions associated with package 8180 mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids); 8181 } 8182 } 8183 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 8184 } 8185 } 8186 // can downgrade to reader 8187 if (writeSettings) { 8188 // Save settings now 8189 mSettings.writeLPr(); 8190 } 8191 } 8192 } 8193 8194 /* 8195 * Tries to delete system package. 8196 */ 8197 private boolean deleteSystemPackageLI(PackageSetting newPs, 8198 int flags, PackageRemovedInfo outInfo, boolean writeSettings) { 8199 PackageSetting disabledPs = null; 8200 // Confirm if the system package has been updated 8201 // An updated system app can be deleted. This will also have to restore 8202 // the system pkg from system partition 8203 // reader 8204 synchronized (mPackages) { 8205 disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name); 8206 } 8207 if (disabledPs == null) { 8208 Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name); 8209 return false; 8210 } else { 8211 Log.i(TAG, "Deleting system pkg from data partition"); 8212 } 8213 // Delete the updated package 8214 outInfo.isRemovedPackageSystemUpdate = true; 8215 if (disabledPs.versionCode < newPs.versionCode) { 8216 // Delete data for downgrades 8217 flags &= ~PackageManager.DELETE_KEEP_DATA; 8218 } else { 8219 // Preserve data by setting flag 8220 flags |= PackageManager.DELETE_KEEP_DATA; 8221 } 8222 boolean ret = deleteInstalledPackageLI(newPs, true, flags, outInfo, 8223 writeSettings); 8224 if (!ret) { 8225 return false; 8226 } 8227 // writer 8228 synchronized (mPackages) { 8229 // Reinstate the old system package 8230 mSettings.enableSystemPackageLPw(newPs.name); 8231 // Remove any native libraries from the upgraded package. 8232 NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString); 8233 } 8234 // Install the system package 8235 PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath, 8236 PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM, 8237 SCAN_MONITOR | SCAN_NO_PATHS, 0, null); 8238 8239 if (newPkg == null) { 8240 Slog.w(TAG, "Failed to restore system package:" + newPs.name 8241 + " with error:" + mLastScanError); 8242 return false; 8243 } 8244 // writer 8245 synchronized (mPackages) { 8246 updatePermissionsLPw(newPkg.packageName, newPkg, 8247 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 8248 // can downgrade to reader here 8249 if (writeSettings) { 8250 mSettings.writeLPr(); 8251 } 8252 } 8253 return true; 8254 } 8255 8256 private boolean deleteInstalledPackageLI(PackageSetting ps, 8257 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo, 8258 boolean writeSettings) { 8259 if (outInfo != null) { 8260 outInfo.uid = ps.appId; 8261 } 8262 8263 // Delete package data from internal structures and also remove data if flag is set 8264 removePackageDataLI(ps, outInfo, flags, writeSettings); 8265 8266 // Delete application code and resources 8267 if (deleteCodeAndResources) { 8268 outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString, 8269 ps.resourcePathString, ps.nativeLibraryPathString); 8270 } 8271 return true; 8272 } 8273 8274 /* 8275 * This method handles package deletion in general 8276 */ 8277 private boolean deletePackageLI(String packageName, UserHandle user, 8278 boolean deleteCodeAndResources, int flags, PackageRemovedInfo outInfo, 8279 boolean writeSettings) { 8280 if (packageName == null) { 8281 Slog.w(TAG, "Attempt to delete null packageName."); 8282 return false; 8283 } 8284 PackageSetting ps; 8285 boolean dataOnly = false; 8286 int removeUser = -1; 8287 int appId = -1; 8288 synchronized (mPackages) { 8289 ps = mSettings.mPackages.get(packageName); 8290 if (ps == null) { 8291 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 8292 return false; 8293 } 8294 if (!isSystemApp(ps) && user != null 8295 && user.getIdentifier() != UserHandle.USER_ALL) { 8296 // The caller is asking that the package only be deleted for a single 8297 // user. To do this, we just mark its uninstalled state and delete 8298 // its data. 8299 ps.setUserState(user.getIdentifier(), 8300 COMPONENT_ENABLED_STATE_DEFAULT, 8301 false, //installed 8302 true, //stopped 8303 true, //notLaunched 8304 null, null); 8305 if (ps.isAnyInstalled(sUserManager.getUserIds())) { 8306 // Other user still have this package installed, so all 8307 // we need to do is clear this user's data and save that 8308 // it is uninstalled. 8309 removeUser = user.getIdentifier(); 8310 appId = ps.appId; 8311 mSettings.writePackageRestrictionsLPr(removeUser); 8312 } else { 8313 // We need to set it back to 'installed' so the uninstall 8314 // broadcasts will be sent correctly. 8315 ps.setInstalled(true, user.getIdentifier()); 8316 } 8317 } 8318 } 8319 8320 if (removeUser >= 0) { 8321 // From above, we determined that we are deleting this only 8322 // for a single user. Continue the work here. 8323 if (outInfo != null) { 8324 outInfo.removedPackage = packageName; 8325 outInfo.removedAppId = appId; 8326 outInfo.removedUsers = new int[] {removeUser}; 8327 } 8328 mInstaller.clearUserData(packageName, removeUser); 8329 schedulePackageCleaning(packageName, removeUser, false); 8330 return true; 8331 } 8332 8333 if (dataOnly) { 8334 // Delete application data first 8335 removePackageDataLI(ps, outInfo, flags, writeSettings); 8336 return true; 8337 } 8338 boolean ret = false; 8339 if (isSystemApp(ps)) { 8340 Log.i(TAG, "Removing system package:" + ps.name); 8341 // When an updated system application is deleted we delete the existing resources as well and 8342 // fall back to existing code in system partition 8343 ret = deleteSystemPackageLI(ps, flags, outInfo, writeSettings); 8344 } else { 8345 Log.i(TAG, "Removing non-system package:" + ps.name); 8346 // Kill application pre-emptively especially for apps on sd. 8347 killApplication(packageName, ps.appId); 8348 ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags, outInfo, 8349 writeSettings); 8350 } 8351 return ret; 8352 } 8353 8354 private final class ClearStorageConnection implements ServiceConnection { 8355 IMediaContainerService mContainerService; 8356 8357 @Override 8358 public void onServiceConnected(ComponentName name, IBinder service) { 8359 synchronized (this) { 8360 mContainerService = IMediaContainerService.Stub.asInterface(service); 8361 notifyAll(); 8362 } 8363 } 8364 8365 @Override 8366 public void onServiceDisconnected(ComponentName name) { 8367 } 8368 } 8369 8370 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 8371 final boolean mounted; 8372 if (Environment.isExternalStorageEmulated()) { 8373 mounted = true; 8374 } else { 8375 final String status = Environment.getExternalStorageState(); 8376 8377 mounted = status.equals(Environment.MEDIA_MOUNTED) 8378 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 8379 } 8380 8381 if (!mounted) { 8382 return; 8383 } 8384 8385 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 8386 int[] users; 8387 if (userId == UserHandle.USER_ALL) { 8388 users = sUserManager.getUserIds(); 8389 } else { 8390 users = new int[] { userId }; 8391 } 8392 final ClearStorageConnection conn = new ClearStorageConnection(); 8393 if (mContext.bindService( 8394 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.USER_OWNER)) { 8395 try { 8396 for (int curUser : users) { 8397 long timeout = SystemClock.uptimeMillis() + 5000; 8398 synchronized (conn) { 8399 long now = SystemClock.uptimeMillis(); 8400 while (conn.mContainerService == null && now < timeout) { 8401 try { 8402 conn.wait(timeout - now); 8403 } catch (InterruptedException e) { 8404 } 8405 } 8406 } 8407 if (conn.mContainerService == null) { 8408 return; 8409 } 8410 8411 final UserEnvironment userEnv = new UserEnvironment(curUser); 8412 final File externalCacheDir = userEnv 8413 .getExternalStorageAppCacheDirectory(packageName); 8414 try { 8415 conn.mContainerService.clearDirectory(externalCacheDir.toString()); 8416 } catch (RemoteException e) { 8417 } 8418 if (allData) { 8419 final File externalDataDir = userEnv 8420 .getExternalStorageAppDataDirectory(packageName); 8421 try { 8422 conn.mContainerService.clearDirectory(externalDataDir.toString()); 8423 } catch (RemoteException e) { 8424 } 8425 final File externalMediaDir = userEnv 8426 .getExternalStorageAppMediaDirectory(packageName); 8427 try { 8428 conn.mContainerService.clearDirectory(externalMediaDir.toString()); 8429 } catch (RemoteException e) { 8430 } 8431 } 8432 } 8433 } finally { 8434 mContext.unbindService(conn); 8435 } 8436 } 8437 } 8438 8439 @Override 8440 public void clearApplicationUserData(final String packageName, 8441 final IPackageDataObserver observer, final int userId) { 8442 mContext.enforceCallingOrSelfPermission( 8443 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 8444 enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data"); 8445 // Queue up an async operation since the package deletion may take a little while. 8446 mHandler.post(new Runnable() { 8447 public void run() { 8448 mHandler.removeCallbacks(this); 8449 final boolean succeeded; 8450 synchronized (mInstallLock) { 8451 succeeded = clearApplicationUserDataLI(packageName, userId); 8452 } 8453 clearExternalStorageDataSync(packageName, userId, true); 8454 if (succeeded) { 8455 // invoke DeviceStorageMonitor's update method to clear any notifications 8456 DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) 8457 ServiceManager.getService(DeviceStorageMonitorService.SERVICE); 8458 if (dsm != null) { 8459 dsm.updateMemory(); 8460 } 8461 } 8462 if(observer != null) { 8463 try { 8464 observer.onRemoveCompleted(packageName, succeeded); 8465 } catch (RemoteException e) { 8466 Log.i(TAG, "Observer no longer exists."); 8467 } 8468 } //end if observer 8469 } //end run 8470 }); 8471 } 8472 8473 private boolean clearApplicationUserDataLI(String packageName, int userId) { 8474 if (packageName == null) { 8475 Slog.w(TAG, "Attempt to delete null packageName."); 8476 return false; 8477 } 8478 PackageParser.Package p; 8479 boolean dataOnly = false; 8480 synchronized (mPackages) { 8481 p = mPackages.get(packageName); 8482 if(p == null) { 8483 dataOnly = true; 8484 PackageSetting ps = mSettings.mPackages.get(packageName); 8485 if((ps == null) || (ps.pkg == null)) { 8486 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8487 return false; 8488 } 8489 p = ps.pkg; 8490 } 8491 } 8492 8493 if (!dataOnly) { 8494 //need to check this only for fully installed applications 8495 if (p == null) { 8496 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8497 return false; 8498 } 8499 final ApplicationInfo applicationInfo = p.applicationInfo; 8500 if (applicationInfo == null) { 8501 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8502 return false; 8503 } 8504 } 8505 int retCode = mInstaller.clearUserData(packageName, userId); 8506 if (retCode < 0) { 8507 Slog.w(TAG, "Couldn't remove cache files for package: " 8508 + packageName); 8509 return false; 8510 } 8511 return true; 8512 } 8513 8514 public void deleteApplicationCacheFiles(final String packageName, 8515 final IPackageDataObserver observer) { 8516 mContext.enforceCallingOrSelfPermission( 8517 android.Manifest.permission.DELETE_CACHE_FILES, null); 8518 // Queue up an async operation since the package deletion may take a little while. 8519 final int userId = UserHandle.getCallingUserId(); 8520 mHandler.post(new Runnable() { 8521 public void run() { 8522 mHandler.removeCallbacks(this); 8523 final boolean succeded; 8524 synchronized (mInstallLock) { 8525 succeded = deleteApplicationCacheFilesLI(packageName, userId); 8526 } 8527 clearExternalStorageDataSync(packageName, userId, false); 8528 if(observer != null) { 8529 try { 8530 observer.onRemoveCompleted(packageName, succeded); 8531 } catch (RemoteException e) { 8532 Log.i(TAG, "Observer no longer exists."); 8533 } 8534 } //end if observer 8535 } //end run 8536 }); 8537 } 8538 8539 private boolean deleteApplicationCacheFilesLI(String packageName, int userId) { 8540 if (packageName == null) { 8541 Slog.w(TAG, "Attempt to delete null packageName."); 8542 return false; 8543 } 8544 PackageParser.Package p; 8545 synchronized (mPackages) { 8546 p = mPackages.get(packageName); 8547 } 8548 if (p == null) { 8549 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8550 return false; 8551 } 8552 final ApplicationInfo applicationInfo = p.applicationInfo; 8553 if (applicationInfo == null) { 8554 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8555 return false; 8556 } 8557 int retCode = mInstaller.deleteCacheFiles(packageName, userId); 8558 if (retCode < 0) { 8559 Slog.w(TAG, "Couldn't remove cache files for package: " 8560 + packageName + " u" + userId); 8561 return false; 8562 } 8563 return true; 8564 } 8565 8566 public void getPackageSizeInfo(final String packageName, int userHandle, 8567 final IPackageStatsObserver observer) { 8568 mContext.enforceCallingOrSelfPermission( 8569 android.Manifest.permission.GET_PACKAGE_SIZE, null); 8570 8571 PackageStats stats = new PackageStats(packageName, userHandle); 8572 8573 /* 8574 * Queue up an async operation since the package measurement may take a 8575 * little while. 8576 */ 8577 Message msg = mHandler.obtainMessage(INIT_COPY); 8578 msg.obj = new MeasureParams(stats, observer); 8579 mHandler.sendMessage(msg); 8580 } 8581 8582 private boolean getPackageSizeInfoLI(String packageName, int userHandle, 8583 PackageStats pStats) { 8584 if (packageName == null) { 8585 Slog.w(TAG, "Attempt to get size of null packageName."); 8586 return false; 8587 } 8588 PackageParser.Package p; 8589 boolean dataOnly = false; 8590 String asecPath = null; 8591 synchronized (mPackages) { 8592 p = mPackages.get(packageName); 8593 if(p == null) { 8594 dataOnly = true; 8595 PackageSetting ps = mSettings.mPackages.get(packageName); 8596 if((ps == null) || (ps.pkg == null)) { 8597 Slog.w(TAG, "Package named '" + packageName +"' doesn't exist."); 8598 return false; 8599 } 8600 p = ps.pkg; 8601 } 8602 if (p != null && (isExternal(p) || isForwardLocked(p))) { 8603 String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir); 8604 if (secureContainerId != null) { 8605 asecPath = PackageHelper.getSdFilesystem(secureContainerId); 8606 } 8607 } 8608 } 8609 String publicSrcDir = null; 8610 if(!dataOnly) { 8611 final ApplicationInfo applicationInfo = p.applicationInfo; 8612 if (applicationInfo == null) { 8613 Slog.w(TAG, "Package " + packageName + " has no applicationInfo."); 8614 return false; 8615 } 8616 if (isForwardLocked(p)) { 8617 publicSrcDir = applicationInfo.publicSourceDir; 8618 } 8619 } 8620 int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, publicSrcDir, 8621 asecPath, pStats); 8622 if (res < 0) { 8623 return false; 8624 } 8625 8626 // Fix-up for forward-locked applications in ASEC containers. 8627 if (!isExternal(p)) { 8628 pStats.codeSize += pStats.externalCodeSize; 8629 pStats.externalCodeSize = 0L; 8630 } 8631 8632 return true; 8633 } 8634 8635 8636 public void addPackageToPreferred(String packageName) { 8637 Slog.w(TAG, "addPackageToPreferred: this is now a no-op"); 8638 } 8639 8640 public void removePackageFromPreferred(String packageName) { 8641 Slog.w(TAG, "removePackageFromPreferred: this is now a no-op"); 8642 } 8643 8644 public List<PackageInfo> getPreferredPackages(int flags) { 8645 return new ArrayList<PackageInfo>(); 8646 } 8647 8648 private int getUidTargetSdkVersionLockedLPr(int uid) { 8649 Object obj = mSettings.getUserIdLPr(uid); 8650 if (obj instanceof SharedUserSetting) { 8651 final SharedUserSetting sus = (SharedUserSetting) obj; 8652 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 8653 final Iterator<PackageSetting> it = sus.packages.iterator(); 8654 while (it.hasNext()) { 8655 final PackageSetting ps = it.next(); 8656 if (ps.pkg != null) { 8657 int v = ps.pkg.applicationInfo.targetSdkVersion; 8658 if (v < vers) vers = v; 8659 } 8660 } 8661 return vers; 8662 } else if (obj instanceof PackageSetting) { 8663 final PackageSetting ps = (PackageSetting) obj; 8664 if (ps.pkg != null) { 8665 return ps.pkg.applicationInfo.targetSdkVersion; 8666 } 8667 } 8668 return Build.VERSION_CODES.CUR_DEVELOPMENT; 8669 } 8670 8671 public void addPreferredActivity(IntentFilter filter, int match, 8672 ComponentName[] set, ComponentName activity, int userId) { 8673 // writer 8674 int callingUid = Binder.getCallingUid(); 8675 enforceCrossUserPermission(callingUid, userId, true, "add preferred activity"); 8676 synchronized (mPackages) { 8677 if (mContext.checkCallingOrSelfPermission( 8678 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8679 != PackageManager.PERMISSION_GRANTED) { 8680 if (getUidTargetSdkVersionLockedLPr(callingUid) 8681 < Build.VERSION_CODES.FROYO) { 8682 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 8683 + callingUid); 8684 return; 8685 } 8686 mContext.enforceCallingOrSelfPermission( 8687 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8688 } 8689 8690 Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :"); 8691 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 8692 mSettings.editPreferredActivitiesLPw(userId).addFilter( 8693 new PreferredActivity(filter, match, set, activity)); 8694 mSettings.writePackageRestrictionsLPr(userId); 8695 } 8696 } 8697 8698 public void replacePreferredActivity(IntentFilter filter, int match, 8699 ComponentName[] set, ComponentName activity) { 8700 if (filter.countActions() != 1) { 8701 throw new IllegalArgumentException( 8702 "replacePreferredActivity expects filter to have only 1 action."); 8703 } 8704 if (filter.countCategories() != 1) { 8705 throw new IllegalArgumentException( 8706 "replacePreferredActivity expects filter to have only 1 category."); 8707 } 8708 if (filter.countDataAuthorities() != 0 8709 || filter.countDataPaths() != 0 8710 || filter.countDataSchemes() != 0 8711 || filter.countDataTypes() != 0) { 8712 throw new IllegalArgumentException( 8713 "replacePreferredActivity expects filter to have no data authorities, " + 8714 "paths, schemes or types."); 8715 } 8716 synchronized (mPackages) { 8717 if (mContext.checkCallingOrSelfPermission( 8718 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8719 != PackageManager.PERMISSION_GRANTED) { 8720 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 8721 < Build.VERSION_CODES.FROYO) { 8722 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 8723 + Binder.getCallingUid()); 8724 return; 8725 } 8726 mContext.enforceCallingOrSelfPermission( 8727 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8728 } 8729 8730 final int callingUserId = UserHandle.getCallingUserId(); 8731 ArrayList<PreferredActivity> removed = null; 8732 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId); 8733 if (pir != null) { 8734 Iterator<PreferredActivity> it = pir.filterIterator(); 8735 String action = filter.getAction(0); 8736 String category = filter.getCategory(0); 8737 while (it.hasNext()) { 8738 PreferredActivity pa = it.next(); 8739 if (pa.getAction(0).equals(action) && pa.getCategory(0).equals(category)) { 8740 if (removed == null) { 8741 removed = new ArrayList<PreferredActivity>(); 8742 } 8743 removed.add(pa); 8744 Log.i(TAG, "Removing preferred activity " + pa.mPref.mComponent + ":"); 8745 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 8746 } 8747 } 8748 if (removed != null) { 8749 for (int i=0; i<removed.size(); i++) { 8750 PreferredActivity pa = removed.get(i); 8751 pir.removeFilter(pa); 8752 } 8753 } 8754 } 8755 addPreferredActivity(filter, match, set, activity, callingUserId); 8756 } 8757 } 8758 8759 public void clearPackagePreferredActivities(String packageName) { 8760 final int uid = Binder.getCallingUid(); 8761 // writer 8762 synchronized (mPackages) { 8763 PackageParser.Package pkg = mPackages.get(packageName); 8764 if (pkg == null || pkg.applicationInfo.uid != uid) { 8765 if (mContext.checkCallingOrSelfPermission( 8766 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 8767 != PackageManager.PERMISSION_GRANTED) { 8768 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 8769 < Build.VERSION_CODES.FROYO) { 8770 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 8771 + Binder.getCallingUid()); 8772 return; 8773 } 8774 mContext.enforceCallingOrSelfPermission( 8775 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 8776 } 8777 } 8778 8779 if (clearPackagePreferredActivitiesLPw(packageName, UserHandle.getCallingUserId())) { 8780 scheduleWriteSettingsLocked(); 8781 } 8782 } 8783 } 8784 8785 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 8786 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 8787 ArrayList<PreferredActivity> removed = null; 8788 boolean changed = false; 8789 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 8790 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 8791 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 8792 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 8793 continue; 8794 } 8795 Iterator<PreferredActivity> it = pir.filterIterator(); 8796 while (it.hasNext()) { 8797 PreferredActivity pa = it.next(); 8798 if (pa.mPref.mComponent.getPackageName().equals(packageName)) { 8799 if (removed == null) { 8800 removed = new ArrayList<PreferredActivity>(); 8801 } 8802 removed.add(pa); 8803 } 8804 } 8805 if (removed != null) { 8806 for (int j=0; j<removed.size(); j++) { 8807 PreferredActivity pa = removed.get(j); 8808 pir.removeFilter(pa); 8809 } 8810 changed = true; 8811 mSettings.writePackageRestrictionsLPr(thisUserId); 8812 } 8813 } 8814 return changed; 8815 } 8816 8817 public int getPreferredActivities(List<IntentFilter> outFilters, 8818 List<ComponentName> outActivities, String packageName) { 8819 8820 int num = 0; 8821 final int userId = UserHandle.getCallingUserId(); 8822 // reader 8823 synchronized (mPackages) { 8824 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 8825 if (pir != null) { 8826 final Iterator<PreferredActivity> it = pir.filterIterator(); 8827 while (it.hasNext()) { 8828 final PreferredActivity pa = it.next(); 8829 if (packageName == null 8830 || pa.mPref.mComponent.getPackageName().equals(packageName)) { 8831 if (outFilters != null) { 8832 outFilters.add(new IntentFilter(pa)); 8833 } 8834 if (outActivities != null) { 8835 outActivities.add(pa.mPref.mComponent); 8836 } 8837 } 8838 } 8839 } 8840 } 8841 8842 return num; 8843 } 8844 8845 @Override 8846 public void setApplicationEnabledSetting(String appPackageName, 8847 int newState, int flags, int userId) { 8848 if (!sUserManager.exists(userId)) return; 8849 setEnabledSetting(appPackageName, null, newState, flags, userId); 8850 } 8851 8852 @Override 8853 public void setComponentEnabledSetting(ComponentName componentName, 8854 int newState, int flags, int userId) { 8855 if (!sUserManager.exists(userId)) return; 8856 setEnabledSetting(componentName.getPackageName(), 8857 componentName.getClassName(), newState, flags, userId); 8858 } 8859 8860 private void setEnabledSetting( 8861 final String packageName, String className, int newState, final int flags, int userId) { 8862 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 8863 || newState == COMPONENT_ENABLED_STATE_ENABLED 8864 || newState == COMPONENT_ENABLED_STATE_DISABLED 8865 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER)) { 8866 throw new IllegalArgumentException("Invalid new component state: " 8867 + newState); 8868 } 8869 PackageSetting pkgSetting; 8870 final int uid = Binder.getCallingUid(); 8871 final int permission = mContext.checkCallingPermission( 8872 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 8873 enforceCrossUserPermission(uid, userId, false, "set enabled"); 8874 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 8875 boolean sendNow = false; 8876 boolean isApp = (className == null); 8877 String componentName = isApp ? packageName : className; 8878 int packageUid = -1; 8879 ArrayList<String> components; 8880 8881 // writer 8882 synchronized (mPackages) { 8883 pkgSetting = mSettings.mPackages.get(packageName); 8884 if (pkgSetting == null) { 8885 if (className == null) { 8886 throw new IllegalArgumentException( 8887 "Unknown package: " + packageName); 8888 } 8889 throw new IllegalArgumentException( 8890 "Unknown component: " + packageName 8891 + "/" + className); 8892 } 8893 // Allow root and verify that userId is not being specified by a different user 8894 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 8895 throw new SecurityException( 8896 "Permission Denial: attempt to change component state from pid=" 8897 + Binder.getCallingPid() 8898 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 8899 } 8900 if (className == null) { 8901 // We're dealing with an application/package level state change 8902 if (pkgSetting.getEnabled(userId) == newState) { 8903 // Nothing to do 8904 return; 8905 } 8906 pkgSetting.setEnabled(newState, userId); 8907 // pkgSetting.pkg.mSetEnabled = newState; 8908 } else { 8909 // We're dealing with a component level state change 8910 // First, verify that this is a valid class name. 8911 PackageParser.Package pkg = pkgSetting.pkg; 8912 if (pkg == null || !pkg.hasComponentClassName(className)) { 8913 if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) { 8914 throw new IllegalArgumentException("Component class " + className 8915 + " does not exist in " + packageName); 8916 } else { 8917 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 8918 + className + " does not exist in " + packageName); 8919 } 8920 } 8921 switch (newState) { 8922 case COMPONENT_ENABLED_STATE_ENABLED: 8923 if (!pkgSetting.enableComponentLPw(className, userId)) { 8924 return; 8925 } 8926 break; 8927 case COMPONENT_ENABLED_STATE_DISABLED: 8928 if (!pkgSetting.disableComponentLPw(className, userId)) { 8929 return; 8930 } 8931 break; 8932 case COMPONENT_ENABLED_STATE_DEFAULT: 8933 if (!pkgSetting.restoreComponentLPw(className, userId)) { 8934 return; 8935 } 8936 break; 8937 default: 8938 Slog.e(TAG, "Invalid new component state: " + newState); 8939 return; 8940 } 8941 } 8942 mSettings.writePackageRestrictionsLPr(userId); 8943 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 8944 components = mPendingBroadcasts.get(packageName); 8945 final boolean newPackage = components == null; 8946 if (newPackage) { 8947 components = new ArrayList<String>(); 8948 } 8949 if (!components.contains(componentName)) { 8950 components.add(componentName); 8951 } 8952 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 8953 sendNow = true; 8954 // Purge entry from pending broadcast list if another one exists already 8955 // since we are sending one right away. 8956 mPendingBroadcasts.remove(packageName); 8957 } else { 8958 if (newPackage) { 8959 mPendingBroadcasts.put(packageName, components); 8960 } 8961 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 8962 // Schedule a message 8963 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 8964 } 8965 } 8966 } 8967 8968 long callingId = Binder.clearCallingIdentity(); 8969 try { 8970 if (sendNow) { 8971 sendPackageChangedBroadcast(packageName, 8972 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 8973 } 8974 } finally { 8975 Binder.restoreCallingIdentity(callingId); 8976 } 8977 } 8978 8979 private void sendPackageChangedBroadcast(String packageName, 8980 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 8981 if (DEBUG_INSTALL) 8982 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 8983 + componentNames); 8984 Bundle extras = new Bundle(4); 8985 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 8986 String nameList[] = new String[componentNames.size()]; 8987 componentNames.toArray(nameList); 8988 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 8989 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 8990 extras.putInt(Intent.EXTRA_UID, packageUid); 8991 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, null, null, 8992 new int[] {UserHandle.getUserId(packageUid)}); 8993 } 8994 8995 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 8996 if (!sUserManager.exists(userId)) return; 8997 final int uid = Binder.getCallingUid(); 8998 final int permission = mContext.checkCallingOrSelfPermission( 8999 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 9000 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 9001 enforceCrossUserPermission(uid, userId, true, "stop package"); 9002 // writer 9003 synchronized (mPackages) { 9004 if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission, 9005 uid, userId)) { 9006 scheduleWritePackageRestrictionsLocked(userId); 9007 } 9008 } 9009 } 9010 9011 public String getInstallerPackageName(String packageName) { 9012 // reader 9013 synchronized (mPackages) { 9014 return mSettings.getInstallerPackageNameLPr(packageName); 9015 } 9016 } 9017 9018 @Override 9019 public int getApplicationEnabledSetting(String packageName, int userId) { 9020 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 9021 int uid = Binder.getCallingUid(); 9022 enforceCrossUserPermission(uid, userId, false, "get enabled"); 9023 // reader 9024 synchronized (mPackages) { 9025 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 9026 } 9027 } 9028 9029 @Override 9030 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 9031 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 9032 int uid = Binder.getCallingUid(); 9033 enforceCrossUserPermission(uid, userId, false, "get component enabled"); 9034 // reader 9035 synchronized (mPackages) { 9036 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 9037 } 9038 } 9039 9040 public void enterSafeMode() { 9041 enforceSystemOrRoot("Only the system can request entering safe mode"); 9042 9043 if (!mSystemReady) { 9044 mSafeMode = true; 9045 } 9046 } 9047 9048 public void systemReady() { 9049 mSystemReady = true; 9050 9051 // Read the compatibilty setting when the system is ready. 9052 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 9053 mContext.getContentResolver(), 9054 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 9055 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 9056 if (DEBUG_SETTINGS) { 9057 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 9058 } 9059 9060 synchronized (mPackages) { 9061 // Verify that all of the preferred activity components actually 9062 // exist. It is possible for applications to be updated and at 9063 // that point remove a previously declared activity component that 9064 // had been set as a preferred activity. We try to clean this up 9065 // the next time we encounter that preferred activity, but it is 9066 // possible for the user flow to never be able to return to that 9067 // situation so here we do a sanity check to make sure we haven't 9068 // left any junk around. 9069 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 9070 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 9071 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 9072 removed.clear(); 9073 for (PreferredActivity pa : pir.filterSet()) { 9074 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 9075 removed.add(pa); 9076 } 9077 } 9078 if (removed.size() > 0) { 9079 for (int j=0; j<removed.size(); j++) { 9080 PreferredActivity pa = removed.get(i); 9081 RuntimeException here = new RuntimeException("here"); 9082 here.fillInStackTrace(); 9083 Slog.w(TAG, "Removing dangling preferred activity: " 9084 + pa.mPref.mComponent, here); 9085 pir.removeFilter(pa); 9086 } 9087 mSettings.writePackageRestrictionsLPr( 9088 mSettings.mPreferredActivities.keyAt(i)); 9089 } 9090 } 9091 } 9092 } 9093 9094 public boolean isSafeMode() { 9095 return mSafeMode; 9096 } 9097 9098 public boolean hasSystemUidErrors() { 9099 return mHasSystemUidErrors; 9100 } 9101 9102 static String arrayToString(int[] array) { 9103 StringBuffer buf = new StringBuffer(128); 9104 buf.append('['); 9105 if (array != null) { 9106 for (int i=0; i<array.length; i++) { 9107 if (i > 0) buf.append(", "); 9108 buf.append(array[i]); 9109 } 9110 } 9111 buf.append(']'); 9112 return buf.toString(); 9113 } 9114 9115 static class DumpState { 9116 public static final int DUMP_LIBS = 1 << 0; 9117 9118 public static final int DUMP_FEATURES = 1 << 1; 9119 9120 public static final int DUMP_RESOLVERS = 1 << 2; 9121 9122 public static final int DUMP_PERMISSIONS = 1 << 3; 9123 9124 public static final int DUMP_PACKAGES = 1 << 4; 9125 9126 public static final int DUMP_SHARED_USERS = 1 << 5; 9127 9128 public static final int DUMP_MESSAGES = 1 << 6; 9129 9130 public static final int DUMP_PROVIDERS = 1 << 7; 9131 9132 public static final int DUMP_VERIFIERS = 1 << 8; 9133 9134 public static final int DUMP_PREFERRED = 1 << 9; 9135 9136 public static final int DUMP_PREFERRED_XML = 1 << 10; 9137 9138 public static final int OPTION_SHOW_FILTERS = 1 << 0; 9139 9140 private int mTypes; 9141 9142 private int mOptions; 9143 9144 private boolean mTitlePrinted; 9145 9146 private SharedUserSetting mSharedUser; 9147 9148 public boolean isDumping(int type) { 9149 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 9150 return true; 9151 } 9152 9153 return (mTypes & type) != 0; 9154 } 9155 9156 public void setDump(int type) { 9157 mTypes |= type; 9158 } 9159 9160 public boolean isOptionEnabled(int option) { 9161 return (mOptions & option) != 0; 9162 } 9163 9164 public void setOptionEnabled(int option) { 9165 mOptions |= option; 9166 } 9167 9168 public boolean onTitlePrinted() { 9169 final boolean printed = mTitlePrinted; 9170 mTitlePrinted = true; 9171 return printed; 9172 } 9173 9174 public boolean getTitlePrinted() { 9175 return mTitlePrinted; 9176 } 9177 9178 public void setTitlePrinted(boolean enabled) { 9179 mTitlePrinted = enabled; 9180 } 9181 9182 public SharedUserSetting getSharedUser() { 9183 return mSharedUser; 9184 } 9185 9186 public void setSharedUser(SharedUserSetting user) { 9187 mSharedUser = user; 9188 } 9189 } 9190 9191 @Override 9192 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 9193 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 9194 != PackageManager.PERMISSION_GRANTED) { 9195 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 9196 + Binder.getCallingPid() 9197 + ", uid=" + Binder.getCallingUid() 9198 + " without permission " 9199 + android.Manifest.permission.DUMP); 9200 return; 9201 } 9202 9203 DumpState dumpState = new DumpState(); 9204 9205 String packageName = null; 9206 9207 int opti = 0; 9208 while (opti < args.length) { 9209 String opt = args[opti]; 9210 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 9211 break; 9212 } 9213 opti++; 9214 if ("-a".equals(opt)) { 9215 // Right now we only know how to print all. 9216 } else if ("-h".equals(opt)) { 9217 pw.println("Package manager dump options:"); 9218 pw.println(" [-h] [-f] [cmd] ..."); 9219 pw.println(" -f: print details of intent filters"); 9220 pw.println(" -h: print this help"); 9221 pw.println(" cmd may be one of:"); 9222 pw.println(" l[ibraries]: list known shared libraries"); 9223 pw.println(" f[ibraries]: list device features"); 9224 pw.println(" r[esolvers]: dump intent resolvers"); 9225 pw.println(" perm[issions]: dump permissions"); 9226 pw.println(" pref[erred]: print preferred package settings"); 9227 pw.println(" preferred-xml: print preferred package settings as xml"); 9228 pw.println(" prov[iders]: dump content providers"); 9229 pw.println(" p[ackages]: dump installed packages"); 9230 pw.println(" s[hared-users]: dump shared user IDs"); 9231 pw.println(" m[essages]: print collected runtime messages"); 9232 pw.println(" v[erifiers]: print package verifier info"); 9233 pw.println(" <package.name>: info about given package"); 9234 return; 9235 } else if ("-f".equals(opt)) { 9236 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 9237 } else { 9238 pw.println("Unknown argument: " + opt + "; use -h for help"); 9239 } 9240 } 9241 9242 // Is the caller requesting to dump a particular piece of data? 9243 if (opti < args.length) { 9244 String cmd = args[opti]; 9245 opti++; 9246 // Is this a package name? 9247 if ("android".equals(cmd) || cmd.contains(".")) { 9248 packageName = cmd; 9249 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 9250 dumpState.setDump(DumpState.DUMP_LIBS); 9251 } else if ("f".equals(cmd) || "features".equals(cmd)) { 9252 dumpState.setDump(DumpState.DUMP_FEATURES); 9253 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 9254 dumpState.setDump(DumpState.DUMP_RESOLVERS); 9255 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 9256 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 9257 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 9258 dumpState.setDump(DumpState.DUMP_PREFERRED); 9259 } else if ("preferred-xml".equals(cmd)) { 9260 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 9261 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 9262 dumpState.setDump(DumpState.DUMP_PACKAGES); 9263 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 9264 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 9265 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 9266 dumpState.setDump(DumpState.DUMP_PROVIDERS); 9267 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 9268 dumpState.setDump(DumpState.DUMP_MESSAGES); 9269 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 9270 dumpState.setDump(DumpState.DUMP_VERIFIERS); 9271 } 9272 } 9273 9274 // reader 9275 synchronized (mPackages) { 9276 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 9277 if (dumpState.onTitlePrinted()) 9278 pw.println(" "); 9279 pw.println("Verifiers:"); 9280 pw.print(" Required: "); 9281 pw.print(mRequiredVerifierPackage); 9282 pw.print(" (uid="); 9283 pw.print(getPackageUid(mRequiredVerifierPackage, 0)); 9284 pw.println(")"); 9285 } 9286 9287 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 9288 if (dumpState.onTitlePrinted()) 9289 pw.println(" "); 9290 pw.println("Libraries:"); 9291 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 9292 while (it.hasNext()) { 9293 String name = it.next(); 9294 pw.print(" "); 9295 pw.print(name); 9296 pw.print(" -> "); 9297 pw.println(mSharedLibraries.get(name)); 9298 } 9299 } 9300 9301 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 9302 if (dumpState.onTitlePrinted()) 9303 pw.println(" "); 9304 pw.println("Features:"); 9305 Iterator<String> it = mAvailableFeatures.keySet().iterator(); 9306 while (it.hasNext()) { 9307 String name = it.next(); 9308 pw.print(" "); 9309 pw.println(name); 9310 } 9311 } 9312 9313 if (dumpState.isDumping(DumpState.DUMP_RESOLVERS)) { 9314 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 9315 : "Activity Resolver Table:", " ", packageName, 9316 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9317 dumpState.setTitlePrinted(true); 9318 } 9319 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 9320 : "Receiver Resolver Table:", " ", packageName, 9321 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9322 dumpState.setTitlePrinted(true); 9323 } 9324 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 9325 : "Service Resolver Table:", " ", packageName, 9326 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9327 dumpState.setTitlePrinted(true); 9328 } 9329 } 9330 9331 if (dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 9332 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 9333 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 9334 int user = mSettings.mPreferredActivities.keyAt(i); 9335 if (pir.dump(pw, 9336 dumpState.getTitlePrinted() 9337 ? "\nPreferred Activities User " + user + ":" 9338 : "Preferred Activities User " + user + ":", " ", 9339 packageName, dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) { 9340 dumpState.setTitlePrinted(true); 9341 } 9342 } 9343 } 9344 9345 if (dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 9346 pw.flush(); 9347 FileOutputStream fout = new FileOutputStream(fd); 9348 BufferedOutputStream str = new BufferedOutputStream(fout); 9349 XmlSerializer serializer = new FastXmlSerializer(); 9350 try { 9351 serializer.setOutput(str, "utf-8"); 9352 serializer.startDocument(null, true); 9353 serializer.setFeature( 9354 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 9355 mSettings.writePreferredActivitiesLPr(serializer, 0); 9356 serializer.endDocument(); 9357 serializer.flush(); 9358 } catch (IllegalArgumentException e) { 9359 pw.println("Failed writing: " + e); 9360 } catch (IllegalStateException e) { 9361 pw.println("Failed writing: " + e); 9362 } catch (IOException e) { 9363 pw.println("Failed writing: " + e); 9364 } 9365 } 9366 9367 if (dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 9368 mSettings.dumpPermissionsLPr(pw, packageName, dumpState); 9369 } 9370 9371 if (dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 9372 boolean printedSomething = false; 9373 for (PackageParser.Provider p : mProvidersByComponent.values()) { 9374 if (packageName != null && !packageName.equals(p.info.packageName)) { 9375 continue; 9376 } 9377 if (!printedSomething) { 9378 if (dumpState.onTitlePrinted()) 9379 pw.println(" "); 9380 pw.println("Registered ContentProviders:"); 9381 printedSomething = true; 9382 } 9383 pw.print(" "); pw.print(p.getComponentShortName()); pw.println(":"); 9384 pw.print(" "); pw.println(p.toString()); 9385 } 9386 printedSomething = false; 9387 for (Map.Entry<String, PackageParser.Provider> entry : mProviders.entrySet()) { 9388 PackageParser.Provider p = entry.getValue(); 9389 if (packageName != null && !packageName.equals(p.info.packageName)) { 9390 continue; 9391 } 9392 if (!printedSomething) { 9393 if (dumpState.onTitlePrinted()) 9394 pw.println(" "); 9395 pw.println("ContentProvider Authorities:"); 9396 printedSomething = true; 9397 } 9398 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 9399 pw.print(" "); pw.println(p.toString()); 9400 if (p.info != null && p.info.applicationInfo != null) { 9401 final String appInfo = p.info.applicationInfo.toString(); 9402 pw.print(" applicationInfo="); pw.println(appInfo); 9403 } 9404 } 9405 } 9406 9407 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 9408 mSettings.dumpPackagesLPr(pw, packageName, dumpState); 9409 } 9410 9411 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 9412 mSettings.dumpSharedUsersLPr(pw, packageName, dumpState); 9413 } 9414 9415 if (dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 9416 if (dumpState.onTitlePrinted()) 9417 pw.println(" "); 9418 mSettings.dumpReadMessagesLPr(pw, dumpState); 9419 9420 pw.println(" "); 9421 pw.println("Package warning messages:"); 9422 final File fname = getSettingsProblemFile(); 9423 FileInputStream in = null; 9424 try { 9425 in = new FileInputStream(fname); 9426 final int avail = in.available(); 9427 final byte[] data = new byte[avail]; 9428 in.read(data); 9429 pw.print(new String(data)); 9430 } catch (FileNotFoundException e) { 9431 } catch (IOException e) { 9432 } finally { 9433 if (in != null) { 9434 try { 9435 in.close(); 9436 } catch (IOException e) { 9437 } 9438 } 9439 } 9440 } 9441 } 9442 } 9443 9444 // ------- apps on sdcard specific code ------- 9445 static final boolean DEBUG_SD_INSTALL = false; 9446 9447 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 9448 9449 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 9450 9451 private boolean mMediaMounted = false; 9452 9453 private String getEncryptKey() { 9454 try { 9455 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 9456 SD_ENCRYPTION_KEYSTORE_NAME); 9457 if (sdEncKey == null) { 9458 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 9459 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 9460 if (sdEncKey == null) { 9461 Slog.e(TAG, "Failed to create encryption keys"); 9462 return null; 9463 } 9464 } 9465 return sdEncKey; 9466 } catch (NoSuchAlgorithmException nsae) { 9467 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 9468 return null; 9469 } catch (IOException ioe) { 9470 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 9471 return null; 9472 } 9473 9474 } 9475 9476 /* package */static String getTempContainerId() { 9477 int tmpIdx = 1; 9478 String list[] = PackageHelper.getSecureContainerList(); 9479 if (list != null) { 9480 for (final String name : list) { 9481 // Ignore null and non-temporary container entries 9482 if (name == null || !name.startsWith(mTempContainerPrefix)) { 9483 continue; 9484 } 9485 9486 String subStr = name.substring(mTempContainerPrefix.length()); 9487 try { 9488 int cid = Integer.parseInt(subStr); 9489 if (cid >= tmpIdx) { 9490 tmpIdx = cid + 1; 9491 } 9492 } catch (NumberFormatException e) { 9493 } 9494 } 9495 } 9496 return mTempContainerPrefix + tmpIdx; 9497 } 9498 9499 /* 9500 * Update media status on PackageManager. 9501 */ 9502 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 9503 int callingUid = Binder.getCallingUid(); 9504 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 9505 throw new SecurityException("Media status can only be updated by the system"); 9506 } 9507 // reader; this apparently protects mMediaMounted, but should probably 9508 // be a different lock in that case. 9509 synchronized (mPackages) { 9510 Log.i(TAG, "Updating external media status from " 9511 + (mMediaMounted ? "mounted" : "unmounted") + " to " 9512 + (mediaStatus ? "mounted" : "unmounted")); 9513 if (DEBUG_SD_INSTALL) 9514 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 9515 + ", mMediaMounted=" + mMediaMounted); 9516 if (mediaStatus == mMediaMounted) { 9517 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 9518 : 0, -1); 9519 mHandler.sendMessage(msg); 9520 return; 9521 } 9522 mMediaMounted = mediaStatus; 9523 } 9524 // Queue up an async operation since the package installation may take a 9525 // little while. 9526 mHandler.post(new Runnable() { 9527 public void run() { 9528 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 9529 } 9530 }); 9531 } 9532 9533 /** 9534 * Called by MountService when the initial ASECs to scan are available. 9535 * Should block until all the ASEC containers are finished being scanned. 9536 */ 9537 public void scanAvailableAsecs() { 9538 updateExternalMediaStatusInner(true, false, false); 9539 } 9540 9541 /* 9542 * Collect information of applications on external media, map them against 9543 * existing containers and update information based on current mount status. 9544 * Please note that we always have to report status if reportStatus has been 9545 * set to true especially when unloading packages. 9546 */ 9547 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 9548 boolean externalStorage) { 9549 // Collection of uids 9550 int uidArr[] = null; 9551 // Collection of stale containers 9552 HashSet<String> removeCids = new HashSet<String>(); 9553 // Collection of packages on external media with valid containers. 9554 HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>(); 9555 // Get list of secure containers. 9556 final String list[] = PackageHelper.getSecureContainerList(); 9557 if (list == null || list.length == 0) { 9558 Log.i(TAG, "No secure containers on sdcard"); 9559 } else { 9560 // Process list of secure containers and categorize them 9561 // as active or stale based on their package internal state. 9562 int uidList[] = new int[list.length]; 9563 int num = 0; 9564 // reader 9565 synchronized (mPackages) { 9566 for (String cid : list) { 9567 if (DEBUG_SD_INSTALL) 9568 Log.i(TAG, "Processing container " + cid); 9569 String pkgName = getAsecPackageName(cid); 9570 if (pkgName == null) { 9571 if (DEBUG_SD_INSTALL) 9572 Log.i(TAG, "Container : " + cid + " stale"); 9573 removeCids.add(cid); 9574 continue; 9575 } 9576 if (DEBUG_SD_INSTALL) 9577 Log.i(TAG, "Looking for pkg : " + pkgName); 9578 9579 final PackageSetting ps = mSettings.mPackages.get(pkgName); 9580 if (ps == null) { 9581 Log.i(TAG, "Deleting container with no matching settings " + cid); 9582 removeCids.add(cid); 9583 continue; 9584 } 9585 9586 /* 9587 * Skip packages that are not external if we're unmounting 9588 * external storage. 9589 */ 9590 if (externalStorage && !isMounted && !isExternal(ps)) { 9591 continue; 9592 } 9593 9594 final AsecInstallArgs args = new AsecInstallArgs(cid, isForwardLocked(ps)); 9595 // The package status is changed only if the code path 9596 // matches between settings and the container id. 9597 if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) { 9598 if (DEBUG_SD_INSTALL) { 9599 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 9600 + " at code path: " + ps.codePathString); 9601 } 9602 9603 // We do have a valid package installed on sdcard 9604 processCids.put(args, ps.codePathString); 9605 final int uid = ps.appId; 9606 if (uid != -1) { 9607 uidList[num++] = uid; 9608 } 9609 } else { 9610 Log.i(TAG, "Deleting stale container for " + cid); 9611 removeCids.add(cid); 9612 } 9613 } 9614 } 9615 9616 if (num > 0) { 9617 // Sort uid list 9618 Arrays.sort(uidList, 0, num); 9619 // Throw away duplicates 9620 uidArr = new int[num]; 9621 uidArr[0] = uidList[0]; 9622 int di = 0; 9623 for (int i = 1; i < num; i++) { 9624 if (uidList[i - 1] != uidList[i]) { 9625 uidArr[di++] = uidList[i]; 9626 } 9627 } 9628 } 9629 } 9630 // Process packages with valid entries. 9631 if (isMounted) { 9632 if (DEBUG_SD_INSTALL) 9633 Log.i(TAG, "Loading packages"); 9634 loadMediaPackages(processCids, uidArr, removeCids); 9635 startCleaningPackages(); 9636 } else { 9637 if (DEBUG_SD_INSTALL) 9638 Log.i(TAG, "Unloading packages"); 9639 unloadMediaPackages(processCids, uidArr, reportStatus); 9640 } 9641 } 9642 9643 private void sendResourcesChangedBroadcast(boolean mediaStatus, ArrayList<String> pkgList, 9644 int uidArr[], IIntentReceiver finishedReceiver) { 9645 int size = pkgList.size(); 9646 if (size > 0) { 9647 // Send broadcasts here 9648 Bundle extras = new Bundle(); 9649 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList 9650 .toArray(new String[size])); 9651 if (uidArr != null) { 9652 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 9653 } 9654 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 9655 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 9656 sendPackageBroadcast(action, null, extras, null, finishedReceiver, null); 9657 } 9658 } 9659 9660 /* 9661 * Look at potentially valid container ids from processCids If package 9662 * information doesn't match the one on record or package scanning fails, 9663 * the cid is added to list of removeCids. We currently don't delete stale 9664 * containers. 9665 */ 9666 private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 9667 HashSet<String> removeCids) { 9668 ArrayList<String> pkgList = new ArrayList<String>(); 9669 Set<AsecInstallArgs> keys = processCids.keySet(); 9670 boolean doGc = false; 9671 for (AsecInstallArgs args : keys) { 9672 String codePath = processCids.get(args); 9673 if (DEBUG_SD_INSTALL) 9674 Log.i(TAG, "Loading container : " + args.cid); 9675 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 9676 try { 9677 // Make sure there are no container errors first. 9678 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 9679 Slog.e(TAG, "Failed to mount cid : " + args.cid 9680 + " when installing from sdcard"); 9681 continue; 9682 } 9683 // Check code path here. 9684 if (codePath == null || !codePath.equals(args.getCodePath())) { 9685 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 9686 + " does not match one in settings " + codePath); 9687 continue; 9688 } 9689 // Parse package 9690 int parseFlags = mDefParseFlags; 9691 if (args.isExternal()) { 9692 parseFlags |= PackageParser.PARSE_ON_SDCARD; 9693 } 9694 if (args.isFwdLocked()) { 9695 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 9696 } 9697 9698 doGc = true; 9699 synchronized (mInstallLock) { 9700 final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags, 9701 0, 0, null); 9702 // Scan the package 9703 if (pkg != null) { 9704 /* 9705 * TODO why is the lock being held? doPostInstall is 9706 * called in other places without the lock. This needs 9707 * to be straightened out. 9708 */ 9709 // writer 9710 synchronized (mPackages) { 9711 retCode = PackageManager.INSTALL_SUCCEEDED; 9712 pkgList.add(pkg.packageName); 9713 // Post process args 9714 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 9715 pkg.applicationInfo.uid); 9716 } 9717 } else { 9718 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 9719 } 9720 } 9721 9722 } finally { 9723 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 9724 // Don't destroy container here. Wait till gc clears things 9725 // up. 9726 removeCids.add(args.cid); 9727 } 9728 } 9729 } 9730 // writer 9731 synchronized (mPackages) { 9732 // If the platform SDK has changed since the last time we booted, 9733 // we need to re-grant app permission to catch any new ones that 9734 // appear. This is really a hack, and means that apps can in some 9735 // cases get permissions that the user didn't initially explicitly 9736 // allow... it would be nice to have some better way to handle 9737 // this situation. 9738 final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion; 9739 if (regrantPermissions) 9740 Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to " 9741 + mSdkVersion + "; regranting permissions for external storage"); 9742 mSettings.mExternalSdkPlatform = mSdkVersion; 9743 9744 // Make sure group IDs have been assigned, and any permission 9745 // changes in other apps are accounted for 9746 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 9747 | (regrantPermissions 9748 ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL) 9749 : 0)); 9750 // can downgrade to reader 9751 // Persist settings 9752 mSettings.writeLPr(); 9753 } 9754 // Send a broadcast to let everyone know we are done processing 9755 if (pkgList.size() > 0) { 9756 sendResourcesChangedBroadcast(true, pkgList, uidArr, null); 9757 } 9758 // Force gc to avoid any stale parser references that we might have. 9759 if (doGc) { 9760 Runtime.getRuntime().gc(); 9761 } 9762 // List stale containers and destroy stale temporary containers. 9763 if (removeCids != null) { 9764 for (String cid : removeCids) { 9765 if (cid.startsWith(mTempContainerPrefix)) { 9766 Log.i(TAG, "Destroying stale temporary container " + cid); 9767 PackageHelper.destroySdDir(cid); 9768 } else { 9769 Log.w(TAG, "Container " + cid + " is stale"); 9770 } 9771 } 9772 } 9773 } 9774 9775 /* 9776 * Utility method to unload a list of specified containers 9777 */ 9778 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 9779 // Just unmount all valid containers. 9780 for (AsecInstallArgs arg : cidArgs) { 9781 synchronized (mInstallLock) { 9782 arg.doPostDeleteLI(false); 9783 } 9784 } 9785 } 9786 9787 /* 9788 * Unload packages mounted on external media. This involves deleting package 9789 * data from internal structures, sending broadcasts about diabled packages, 9790 * gc'ing to free up references, unmounting all secure containers 9791 * corresponding to packages on external media, and posting a 9792 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 9793 * that we always have to post this message if status has been requested no 9794 * matter what. 9795 */ 9796 private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[], 9797 final boolean reportStatus) { 9798 if (DEBUG_SD_INSTALL) 9799 Log.i(TAG, "unloading media packages"); 9800 ArrayList<String> pkgList = new ArrayList<String>(); 9801 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 9802 final Set<AsecInstallArgs> keys = processCids.keySet(); 9803 for (AsecInstallArgs args : keys) { 9804 String pkgName = args.getPackageName(); 9805 if (DEBUG_SD_INSTALL) 9806 Log.i(TAG, "Trying to unload pkg : " + pkgName); 9807 // Delete package internally 9808 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 9809 synchronized (mInstallLock) { 9810 boolean res = deletePackageLI(pkgName, null, false, 9811 PackageManager.DELETE_KEEP_DATA, outInfo, false); 9812 if (res) { 9813 pkgList.add(pkgName); 9814 } else { 9815 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 9816 failedList.add(args); 9817 } 9818 } 9819 } 9820 9821 // reader 9822 synchronized (mPackages) { 9823 // We didn't update the settings after removing each package; 9824 // write them now for all packages. 9825 mSettings.writeLPr(); 9826 } 9827 9828 // We have to absolutely send UPDATED_MEDIA_STATUS only 9829 // after confirming that all the receivers processed the ordered 9830 // broadcast when packages get disabled, force a gc to clean things up. 9831 // and unload all the containers. 9832 if (pkgList.size() > 0) { 9833 sendResourcesChangedBroadcast(false, pkgList, uidArr, new IIntentReceiver.Stub() { 9834 public void performReceive(Intent intent, int resultCode, String data, 9835 Bundle extras, boolean ordered, boolean sticky, 9836 int sendingUser) throws RemoteException { 9837 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 9838 reportStatus ? 1 : 0, 1, keys); 9839 mHandler.sendMessage(msg); 9840 } 9841 }); 9842 } else { 9843 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 9844 keys); 9845 mHandler.sendMessage(msg); 9846 } 9847 } 9848 9849 /** Binder call */ 9850 @Override 9851 public void movePackage(final String packageName, final IPackageMoveObserver observer, 9852 final int flags) { 9853 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 9854 UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 9855 int returnCode = PackageManager.MOVE_SUCCEEDED; 9856 int currFlags = 0; 9857 int newFlags = 0; 9858 // reader 9859 synchronized (mPackages) { 9860 PackageParser.Package pkg = mPackages.get(packageName); 9861 if (pkg == null) { 9862 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9863 } else { 9864 // Disable moving fwd locked apps and system packages 9865 if (pkg.applicationInfo != null && isSystemApp(pkg)) { 9866 Slog.w(TAG, "Cannot move system application"); 9867 returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 9868 } else if (pkg.mOperationPending) { 9869 Slog.w(TAG, "Attempt to move package which has pending operations"); 9870 returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING; 9871 } else { 9872 // Find install location first 9873 if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 9874 && (flags & PackageManager.MOVE_INTERNAL) != 0) { 9875 Slog.w(TAG, "Ambigous flags specified for move location."); 9876 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9877 } else { 9878 newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL 9879 : PackageManager.INSTALL_INTERNAL; 9880 currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL 9881 : PackageManager.INSTALL_INTERNAL; 9882 9883 if (newFlags == currFlags) { 9884 Slog.w(TAG, "No move required. Trying to move to same location"); 9885 returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION; 9886 } else { 9887 if (isForwardLocked(pkg)) { 9888 currFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9889 newFlags |= PackageManager.INSTALL_FORWARD_LOCK; 9890 } 9891 } 9892 } 9893 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9894 pkg.mOperationPending = true; 9895 } 9896 } 9897 } 9898 9899 /* 9900 * TODO this next block probably shouldn't be inside the lock. We 9901 * can't guarantee these won't change after this is fired off 9902 * anyway. 9903 */ 9904 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 9905 processPendingMove(new MoveParams(null, observer, 0, packageName, 9906 null, -1, user), 9907 returnCode); 9908 } else { 9909 Message msg = mHandler.obtainMessage(INIT_COPY); 9910 InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir, 9911 pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir); 9912 MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName, 9913 pkg.applicationInfo.dataDir, pkg.applicationInfo.uid, user); 9914 msg.obj = mp; 9915 mHandler.sendMessage(msg); 9916 } 9917 } 9918 } 9919 9920 private void processPendingMove(final MoveParams mp, final int currentStatus) { 9921 // Queue up an async operation since the package deletion may take a 9922 // little while. 9923 mHandler.post(new Runnable() { 9924 public void run() { 9925 // TODO fix this; this does nothing. 9926 mHandler.removeCallbacks(this); 9927 int returnCode = currentStatus; 9928 if (currentStatus == PackageManager.MOVE_SUCCEEDED) { 9929 int uidArr[] = null; 9930 ArrayList<String> pkgList = null; 9931 synchronized (mPackages) { 9932 PackageParser.Package pkg = mPackages.get(mp.packageName); 9933 if (pkg == null) { 9934 Slog.w(TAG, " Package " + mp.packageName 9935 + " doesn't exist. Aborting move"); 9936 returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST; 9937 } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) { 9938 Slog.w(TAG, "Package " + mp.packageName + " code path changed from " 9939 + mp.srcArgs.getCodePath() + " to " 9940 + pkg.applicationInfo.sourceDir 9941 + " Aborting move and returning error"); 9942 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9943 } else { 9944 uidArr = new int[] { 9945 pkg.applicationInfo.uid 9946 }; 9947 pkgList = new ArrayList<String>(); 9948 pkgList.add(mp.packageName); 9949 } 9950 } 9951 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9952 // Send resources unavailable broadcast 9953 sendResourcesChangedBroadcast(false, pkgList, uidArr, null); 9954 // Update package code and resource paths 9955 synchronized (mInstallLock) { 9956 synchronized (mPackages) { 9957 PackageParser.Package pkg = mPackages.get(mp.packageName); 9958 // Recheck for package again. 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( 9964 pkg.applicationInfo.sourceDir)) { 9965 Slog.w(TAG, "Package " + mp.packageName 9966 + " code path changed from " + mp.srcArgs.getCodePath() 9967 + " to " + pkg.applicationInfo.sourceDir 9968 + " Aborting move and returning error"); 9969 returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR; 9970 } else { 9971 final String oldCodePath = pkg.mPath; 9972 final String newCodePath = mp.targetArgs.getCodePath(); 9973 final String newResPath = mp.targetArgs.getResourcePath(); 9974 final String newNativePath = mp.targetArgs 9975 .getNativeLibraryPath(); 9976 9977 final File newNativeDir = new File(newNativePath); 9978 9979 if (!isForwardLocked(pkg) && !isExternal(pkg)) { 9980 NativeLibraryHelper.copyNativeBinariesIfNeededLI( 9981 new File(newCodePath), newNativeDir); 9982 } 9983 final int[] users = sUserManager.getUserIds(); 9984 for (int user : users) { 9985 if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, 9986 newNativePath, user) < 0) { 9987 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9988 } 9989 } 9990 9991 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 9992 pkg.mPath = newCodePath; 9993 // Move dex files around 9994 if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) { 9995 // Moving of dex files failed. Set 9996 // error code and abort move. 9997 pkg.mPath = pkg.mScanPath; 9998 returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE; 9999 } 10000 } 10001 10002 if (returnCode == PackageManager.MOVE_SUCCEEDED) { 10003 pkg.mScanPath = newCodePath; 10004 pkg.applicationInfo.sourceDir = newCodePath; 10005 pkg.applicationInfo.publicSourceDir = newResPath; 10006 pkg.applicationInfo.nativeLibraryDir = newNativePath; 10007 PackageSetting ps = (PackageSetting) pkg.mExtras; 10008 ps.codePath = new File(pkg.applicationInfo.sourceDir); 10009 ps.codePathString = ps.codePath.getPath(); 10010 ps.resourcePath = new File( 10011 pkg.applicationInfo.publicSourceDir); 10012 ps.resourcePathString = ps.resourcePath.getPath(); 10013 ps.nativeLibraryPathString = newNativePath; 10014 // Set the application info flag 10015 // correctly. 10016 if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) { 10017 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE; 10018 } else { 10019 pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE; 10020 } 10021 ps.setFlags(pkg.applicationInfo.flags); 10022 mAppDirs.remove(oldCodePath); 10023 mAppDirs.put(newCodePath, pkg); 10024 // Persist settings 10025 mSettings.writeLPr(); 10026 } 10027 } 10028 } 10029 } 10030 // Send resources available broadcast 10031 sendResourcesChangedBroadcast(true, pkgList, uidArr, null); 10032 } 10033 } 10034 if (returnCode != PackageManager.MOVE_SUCCEEDED) { 10035 // Clean up failed installation 10036 if (mp.targetArgs != null) { 10037 mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR, 10038 -1); 10039 } 10040 } else { 10041 // Force a gc to clear things up. 10042 Runtime.getRuntime().gc(); 10043 // Delete older code 10044 synchronized (mInstallLock) { 10045 mp.srcArgs.doPostDeleteLI(true); 10046 } 10047 } 10048 10049 // Allow more operations on this file if we didn't fail because 10050 // an operation was already pending for this package. 10051 if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) { 10052 synchronized (mPackages) { 10053 PackageParser.Package pkg = mPackages.get(mp.packageName); 10054 if (pkg != null) { 10055 pkg.mOperationPending = false; 10056 } 10057 } 10058 } 10059 10060 IPackageMoveObserver observer = mp.observer; 10061 if (observer != null) { 10062 try { 10063 observer.packageMoved(mp.packageName, returnCode); 10064 } catch (RemoteException e) { 10065 Log.i(TAG, "Observer no longer exists."); 10066 } 10067 } 10068 } 10069 }); 10070 } 10071 10072 public boolean setInstallLocation(int loc) { 10073 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 10074 null); 10075 if (getInstallLocation() == loc) { 10076 return true; 10077 } 10078 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 10079 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 10080 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 10081 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 10082 return true; 10083 } 10084 return false; 10085 } 10086 10087 public int getInstallLocation() { 10088 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10089 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 10090 PackageHelper.APP_INSTALL_AUTO); 10091 } 10092 10093 /** Called by UserManagerService */ 10094 void cleanUpUserLILPw(int userHandle) { 10095 if (mDirtyUsers.remove(userHandle)); 10096 mSettings.removeUserLPr(userHandle); 10097 if (mInstaller != null) { 10098 // Technically, we shouldn't be doing this with the package lock 10099 // held. However, this is very rare, and there is already so much 10100 // other disk I/O going on, that we'll let it slide for now. 10101 mInstaller.removeUserDataDirs(userHandle); 10102 } 10103 } 10104 10105 /** Called by UserManagerService */ 10106 void createNewUserLILPw(int userHandle, File path) { 10107 if (mInstaller != null) { 10108 mSettings.createNewUserLILPw(mInstaller, userHandle, path); 10109 } 10110 } 10111 10112 @Override 10113 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 10114 mContext.enforceCallingOrSelfPermission( 10115 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 10116 "Only package verification agents can read the verifier device identity"); 10117 10118 synchronized (mPackages) { 10119 return mSettings.getVerifierDeviceIdentityLPw(); 10120 } 10121 } 10122 10123 @Override 10124 public void setPermissionEnforced(String permission, boolean enforced) { 10125 mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null); 10126 if (READ_EXTERNAL_STORAGE.equals(permission)) { 10127 synchronized (mPackages) { 10128 if (mSettings.mReadExternalStorageEnforced == null 10129 || mSettings.mReadExternalStorageEnforced != enforced) { 10130 mSettings.mReadExternalStorageEnforced = enforced; 10131 mSettings.writeLPr(); 10132 10133 // kill any non-foreground processes so we restart them and 10134 // grant/revoke the GID. 10135 final IActivityManager am = ActivityManagerNative.getDefault(); 10136 if (am != null) { 10137 final long token = Binder.clearCallingIdentity(); 10138 try { 10139 am.killProcessesBelowForeground("setPermissionEnforcement"); 10140 } catch (RemoteException e) { 10141 } finally { 10142 Binder.restoreCallingIdentity(token); 10143 } 10144 } 10145 } 10146 } 10147 } else { 10148 throw new IllegalArgumentException("No selective enforcement for " + permission); 10149 } 10150 } 10151 10152 @Override 10153 public boolean isPermissionEnforced(String permission) { 10154 final boolean enforcedDefault = isPermissionEnforcedDefault(permission); 10155 synchronized (mPackages) { 10156 return isPermissionEnforcedLocked(permission, enforcedDefault); 10157 } 10158 } 10159 10160 /** 10161 * Check if given permission should be enforced by default. Should always be 10162 * called outside of {@link #mPackages} lock. 10163 */ 10164 private boolean isPermissionEnforcedDefault(String permission) { 10165 if (READ_EXTERNAL_STORAGE.equals(permission)) { 10166 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 10167 android.provider.Settings.Global.READ_EXTERNAL_STORAGE_ENFORCED_DEFAULT, 0) 10168 != 0; 10169 } else { 10170 return true; 10171 } 10172 } 10173 10174 /** 10175 * Check if user has requested that given permission be enforced, using 10176 * given default if undefined. 10177 */ 10178 private boolean isPermissionEnforcedLocked(String permission, boolean enforcedDefault) { 10179 if (READ_EXTERNAL_STORAGE.equals(permission)) { 10180 if (mSettings.mReadExternalStorageEnforced != null) { 10181 return mSettings.mReadExternalStorageEnforced; 10182 } else { 10183 // User hasn't defined; fall back to secure default 10184 return enforcedDefault; 10185 } 10186 } else { 10187 return true; 10188 } 10189 } 10190 10191 public boolean isStorageLow() { 10192 final long token = Binder.clearCallingIdentity(); 10193 try { 10194 final DeviceStorageMonitorService dsm = (DeviceStorageMonitorService) ServiceManager 10195 .getService(DeviceStorageMonitorService.SERVICE); 10196 return dsm.isMemoryLow(); 10197 } finally { 10198 Binder.restoreCallingIdentity(token); 10199 } 10200 } 10201} 10202