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