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