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