1 /* 2 * Copyright (C) 2006-2008 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 17 package com.android.server.am; 18 19 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 20 21 import android.app.AppOpsManager; 22 import android.appwidget.AppWidgetManager; 23 import com.android.internal.R; 24 import com.android.internal.os.BatteryStatsImpl; 25 import com.android.internal.os.ProcessStats; 26 import com.android.server.AppOpsService; 27 import com.android.server.AttributeCache; 28 import com.android.server.IntentResolver; 29 import com.android.server.ProcessMap; 30 import com.android.server.SystemServer; 31 import com.android.server.Watchdog; 32 import com.android.server.am.ActivityStack.ActivityState; 33 import com.android.server.firewall.IntentFirewall; 34 import com.android.server.pm.UserManagerService; 35 import com.android.server.wm.AppTransition; 36 import com.android.server.wm.WindowManagerService; 37 38 import dalvik.system.Zygote; 39 40 import android.app.Activity; 41 import android.app.ActivityManager; 42 import android.app.ActivityManagerNative; 43 import android.app.ActivityOptions; 44 import android.app.ActivityThread; 45 import android.app.AlertDialog; 46 import android.app.AppGlobals; 47 import android.app.ApplicationErrorReport; 48 import android.app.Dialog; 49 import android.app.IActivityController; 50 import android.app.IApplicationThread; 51 import android.app.IInstrumentationWatcher; 52 import android.app.INotificationManager; 53 import android.app.IProcessObserver; 54 import android.app.IServiceConnection; 55 import android.app.IStopUserCallback; 56 import android.app.IThumbnailReceiver; 57 import android.app.IUiAutomationConnection; 58 import android.app.IUserSwitchObserver; 59 import android.app.Instrumentation; 60 import android.app.Notification; 61 import android.app.NotificationManager; 62 import android.app.PendingIntent; 63 import android.app.backup.IBackupManager; 64 import android.content.ActivityNotFoundException; 65 import android.content.BroadcastReceiver; 66 import android.content.ClipData; 67 import android.content.ComponentCallbacks2; 68 import android.content.ComponentName; 69 import android.content.ContentProvider; 70 import android.content.ContentResolver; 71 import android.content.Context; 72 import android.content.DialogInterface; 73 import android.content.IContentProvider; 74 import android.content.IIntentReceiver; 75 import android.content.IIntentSender; 76 import android.content.Intent; 77 import android.content.IntentFilter; 78 import android.content.IntentSender; 79 import android.content.pm.ActivityInfo; 80 import android.content.pm.ApplicationInfo; 81 import android.content.pm.ConfigurationInfo; 82 import android.content.pm.IPackageDataObserver; 83 import android.content.pm.IPackageManager; 84 import android.content.pm.InstrumentationInfo; 85 import android.content.pm.PackageInfo; 86 import android.content.pm.PackageManager; 87 import android.content.pm.UserInfo; 88 import android.content.pm.PackageManager.NameNotFoundException; 89 import android.content.pm.PathPermission; 90 import android.content.pm.ProviderInfo; 91 import android.content.pm.ResolveInfo; 92 import android.content.pm.ServiceInfo; 93 import android.content.res.CompatibilityInfo; 94 import android.content.res.Configuration; 95 import android.graphics.Bitmap; 96 import android.net.Proxy; 97 import android.net.ProxyProperties; 98 import android.net.Uri; 99 import android.os.Binder; 100 import android.os.Build; 101 import android.os.Bundle; 102 import android.os.Debug; 103 import android.os.DropBoxManager; 104 import android.os.Environment; 105 import android.os.FileObserver; 106 import android.os.FileUtils; 107 import android.os.Handler; 108 import android.os.IBinder; 109 import android.os.IPermissionController; 110 import android.os.IRemoteCallback; 111 import android.os.IUserManager; 112 import android.os.Looper; 113 import android.os.Message; 114 import android.os.Parcel; 115 import android.os.ParcelFileDescriptor; 116 import android.os.Process; 117 import android.os.RemoteCallbackList; 118 import android.os.RemoteException; 119 import android.os.SELinux; 120 import android.os.ServiceManager; 121 import android.os.StrictMode; 122 import android.os.SystemClock; 123 import android.os.SystemProperties; 124 import android.os.UpdateLock; 125 import android.os.UserHandle; 126 import android.provider.Settings; 127 import android.text.format.Time; 128 import android.util.EventLog; 129 import android.util.Log; 130 import android.util.Pair; 131 import android.util.PrintWriterPrinter; 132 import android.util.Slog; 133 import android.util.SparseArray; 134 import android.util.TimeUtils; 135 import android.view.Gravity; 136 import android.view.LayoutInflater; 137 import android.view.View; 138 import android.view.WindowManager; 139 140 import java.io.BufferedInputStream; 141 import java.io.BufferedOutputStream; 142 import java.io.BufferedReader; 143 import java.io.DataInputStream; 144 import java.io.DataOutputStream; 145 import java.io.File; 146 import java.io.FileDescriptor; 147 import java.io.FileInputStream; 148 import java.io.FileNotFoundException; 149 import java.io.FileOutputStream; 150 import java.io.IOException; 151 import java.io.InputStreamReader; 152 import java.io.PrintWriter; 153 import java.io.StringWriter; 154 import java.lang.ref.WeakReference; 155 import java.util.ArrayList; 156 import java.util.Arrays; 157 import java.util.Collections; 158 import java.util.Comparator; 159 import java.util.HashMap; 160 import java.util.HashSet; 161 import java.util.Iterator; 162 import java.util.List; 163 import java.util.Locale; 164 import java.util.Map; 165 import java.util.Set; 166 import java.util.concurrent.atomic.AtomicBoolean; 167 import java.util.concurrent.atomic.AtomicLong; 168 169 public final class ActivityManagerService extends ActivityManagerNative 170 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 171 private static final String USER_DATA_DIR = "/data/user/"; 172 static final String TAG = "ActivityManager"; 173 static final String TAG_MU = "ActivityManagerServiceMU"; 174 static final boolean DEBUG = false; 175 static final boolean localLOGV = DEBUG; 176 static final boolean DEBUG_SWITCH = localLOGV || false; 177 static final boolean DEBUG_TASKS = localLOGV || false; 178 static final boolean DEBUG_THUMBNAILS = localLOGV || false; 179 static final boolean DEBUG_PAUSE = localLOGV || false; 180 static final boolean DEBUG_OOM_ADJ = localLOGV || false; 181 static final boolean DEBUG_TRANSITION = localLOGV || false; 182 static final boolean DEBUG_BROADCAST = localLOGV || false; 183 static final boolean DEBUG_BACKGROUND_BROADCAST = DEBUG_BROADCAST || false; 184 static final boolean DEBUG_BROADCAST_LIGHT = DEBUG_BROADCAST || false; 185 static final boolean DEBUG_SERVICE = localLOGV || false; 186 static final boolean DEBUG_SERVICE_EXECUTING = localLOGV || false; 187 static final boolean DEBUG_VISBILITY = localLOGV || false; 188 static final boolean DEBUG_PROCESSES = localLOGV || false; 189 static final boolean DEBUG_PROCESS_OBSERVERS = localLOGV || false; 190 static final boolean DEBUG_CLEANUP = localLOGV || false; 191 static final boolean DEBUG_PROVIDER = localLOGV || false; 192 static final boolean DEBUG_URI_PERMISSION = localLOGV || false; 193 static final boolean DEBUG_USER_LEAVING = localLOGV || false; 194 static final boolean DEBUG_RESULTS = localLOGV || false; 195 static final boolean DEBUG_BACKUP = localLOGV || false; 196 static final boolean DEBUG_CONFIGURATION = localLOGV || false; 197 static final boolean DEBUG_POWER = localLOGV || false; 198 static final boolean DEBUG_POWER_QUICK = DEBUG_POWER || false; 199 static final boolean DEBUG_MU = localLOGV || false; 200 static final boolean DEBUG_IMMERSIVE = localLOGV || false; 201 static final boolean VALIDATE_TOKENS = false; 202 static final boolean SHOW_ACTIVITY_START_TIME = true; 203 204 // Control over CPU and battery monitoring. 205 static final long BATTERY_STATS_TIME = 30*60*1000; // write battery stats every 30 minutes. 206 static final boolean MONITOR_CPU_USAGE = true; 207 static final long MONITOR_CPU_MIN_TIME = 5*1000; // don't sample cpu less than every 5 seconds. 208 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; // wait possibly forever for next cpu sample. 209 static final boolean MONITOR_THREAD_CPU_USAGE = false; 210 211 // The flags that are set for all calls we make to the package manager. 212 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 213 214 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable"; 215 216 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE); 217 218 // Maximum number of recent tasks that we can remember. 219 static final int MAX_RECENT_TASKS = 20; 220 221 // Amount of time after a call to stopAppSwitches() during which we will 222 // prevent further untrusted switches from happening. 223 static final long APP_SWITCH_DELAY_TIME = 5*1000; 224 225 // How long we wait for a launched process to attach to the activity manager 226 // before we decide it's never going to come up for real. 227 static final int PROC_START_TIMEOUT = 10*1000; 228 229 // How long we wait for a launched process to attach to the activity manager 230 // before we decide it's never going to come up for real, when the process was 231 // started with a wrapper for instrumentation (such as Valgrind) because it 232 // could take much longer than usual. 233 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 300*1000; 234 235 // How long to wait after going idle before forcing apps to GC. 236 static final int GC_TIMEOUT = 5*1000; 237 238 // The minimum amount of time between successive GC requests for a process. 239 static final int GC_MIN_INTERVAL = 60*1000; 240 241 // The rate at which we check for apps using excessive power -- 15 mins. 242 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000; 243 244 // The minimum sample duration we will allow before deciding we have 245 // enough data on wake locks to start killing things. 246 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 247 248 // The minimum sample duration we will allow before deciding we have 249 // enough data on CPU usage to start killing things. 250 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 251 252 // How long we allow a receiver to run before giving up on it. 253 static final int BROADCAST_FG_TIMEOUT = 10*1000; 254 static final int BROADCAST_BG_TIMEOUT = 60*1000; 255 256 // How long we wait until we timeout on key dispatching. 257 static final int KEY_DISPATCHING_TIMEOUT = 5*1000; 258 259 // How long we wait until we timeout on key dispatching during instrumentation. 260 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000; 261 262 // Amount of time we wait for observers to handle a user switch before 263 // giving up on them and unfreezing the screen. 264 static final int USER_SWITCH_TIMEOUT = 2*1000; 265 266 // Maximum number of users we allow to be running at a time. 267 static final int MAX_RUNNING_USERS = 3; 268 269 // How long to wait in getTopActivityExtras for the activity to respond with the result. 270 static final int PENDING_ACTIVITY_RESULT_TIMEOUT = 2*2000; 271 272 static final int MY_PID = Process.myPid(); 273 274 static final String[] EMPTY_STRING_ARRAY = new String[0]; 275 276 public ActivityStack mMainStack; 277 278 public IntentFirewall mIntentFirewall; 279 280 private final boolean mHeadless; 281 282 // Whether we should show our dialogs (ANR, crash, etc) or just perform their 283 // default actuion automatically. Important for devices without direct input 284 // devices. 285 private boolean mShowDialogs = true; 286 287 /** 288 * Description of a request to start a new activity, which has been held 289 * due to app switches being disabled. 290 */ 291 static class PendingActivityLaunch { 292 ActivityRecord r; 293 ActivityRecord sourceRecord; 294 int startFlags; 295 } 296 297 final ArrayList<PendingActivityLaunch> mPendingActivityLaunches 298 = new ArrayList<PendingActivityLaunch>(); 299 300 301 BroadcastQueue mFgBroadcastQueue; 302 BroadcastQueue mBgBroadcastQueue; 303 // Convenient for easy iteration over the queues. Foreground is first 304 // so that dispatch of foreground broadcasts gets precedence. 305 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2]; 306 307 BroadcastQueue broadcastQueueForIntent(Intent intent) { 308 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 309 if (DEBUG_BACKGROUND_BROADCAST) { 310 Slog.i(TAG, "Broadcast intent " + intent + " on " 311 + (isFg ? "foreground" : "background") 312 + " queue"); 313 } 314 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 315 } 316 317 BroadcastRecord broadcastRecordForReceiverLocked(IBinder receiver) { 318 for (BroadcastQueue queue : mBroadcastQueues) { 319 BroadcastRecord r = queue.getMatchingOrderedReceiver(receiver); 320 if (r != null) { 321 return r; 322 } 323 } 324 return null; 325 } 326 327 /** 328 * Activity we have told the window manager to have key focus. 329 */ 330 ActivityRecord mFocusedActivity = null; 331 332 /** 333 * List of intents that were used to start the most recent tasks. 334 */ 335 final ArrayList<TaskRecord> mRecentTasks = new ArrayList<TaskRecord>(); 336 337 public class PendingActivityExtras extends Binder implements Runnable { 338 public final ActivityRecord activity; 339 public boolean haveResult = false; 340 public Bundle result = null; 341 public PendingActivityExtras(ActivityRecord _activity) { 342 activity = _activity; 343 } 344 @Override 345 public void run() { 346 Slog.w(TAG, "getTopActivityExtras failed: timeout retrieving from " + activity); 347 synchronized (this) { 348 haveResult = true; 349 notifyAll(); 350 } 351 } 352 } 353 354 final ArrayList<PendingActivityExtras> mPendingActivityExtras 355 = new ArrayList<PendingActivityExtras>(); 356 357 /** 358 * Process management. 359 */ 360 final ProcessList mProcessList = new ProcessList(); 361 362 /** 363 * All of the applications we currently have running organized by name. 364 * The keys are strings of the application package name (as 365 * returned by the package manager), and the keys are ApplicationRecord 366 * objects. 367 */ 368 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>(); 369 370 /** 371 * The currently running isolated processes. 372 */ 373 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>(); 374 375 /** 376 * Counter for assigning isolated process uids, to avoid frequently reusing the 377 * same ones. 378 */ 379 int mNextIsolatedProcessUid = 0; 380 381 /** 382 * The currently running heavy-weight process, if any. 383 */ 384 ProcessRecord mHeavyWeightProcess = null; 385 386 /** 387 * The last time that various processes have crashed. 388 */ 389 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>(); 390 391 /** 392 * Set of applications that we consider to be bad, and will reject 393 * incoming broadcasts from (which the user has no control over). 394 * Processes are added to this set when they have crashed twice within 395 * a minimum amount of time; they are removed from it when they are 396 * later restarted (hopefully due to some user action). The value is the 397 * time it was added to the list. 398 */ 399 final ProcessMap<Long> mBadProcesses = new ProcessMap<Long>(); 400 401 /** 402 * All of the processes we currently have running organized by pid. 403 * The keys are the pid running the application. 404 * 405 * <p>NOTE: This object is protected by its own lock, NOT the global 406 * activity manager lock! 407 */ 408 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>(); 409 410 /** 411 * All of the processes that have been forced to be foreground. The key 412 * is the pid of the caller who requested it (we hold a death 413 * link on it). 414 */ 415 abstract class ForegroundToken implements IBinder.DeathRecipient { 416 int pid; 417 IBinder token; 418 } 419 final SparseArray<ForegroundToken> mForegroundProcesses 420 = new SparseArray<ForegroundToken>(); 421 422 /** 423 * List of records for processes that someone had tried to start before the 424 * system was ready. We don't start them at that point, but ensure they 425 * are started by the time booting is complete. 426 */ 427 final ArrayList<ProcessRecord> mProcessesOnHold 428 = new ArrayList<ProcessRecord>(); 429 430 /** 431 * List of persistent applications that are in the process 432 * of being started. 433 */ 434 final ArrayList<ProcessRecord> mPersistentStartingProcesses 435 = new ArrayList<ProcessRecord>(); 436 437 /** 438 * Processes that are being forcibly torn down. 439 */ 440 final ArrayList<ProcessRecord> mRemovedProcesses 441 = new ArrayList<ProcessRecord>(); 442 443 /** 444 * List of running applications, sorted by recent usage. 445 * The first entry in the list is the least recently used. 446 * It contains ApplicationRecord objects. This list does NOT include 447 * any persistent application records (since we never want to exit them). 448 */ 449 final ArrayList<ProcessRecord> mLruProcesses 450 = new ArrayList<ProcessRecord>(); 451 452 /** 453 * List of processes that should gc as soon as things are idle. 454 */ 455 final ArrayList<ProcessRecord> mProcessesToGc 456 = new ArrayList<ProcessRecord>(); 457 458 /** 459 * This is the process holding what we currently consider to be 460 * the "home" activity. 461 */ 462 ProcessRecord mHomeProcess; 463 464 /** 465 * This is the process holding the activity the user last visited that 466 * is in a different process from the one they are currently in. 467 */ 468 ProcessRecord mPreviousProcess; 469 470 /** 471 * The time at which the previous process was last visible. 472 */ 473 long mPreviousProcessVisibleTime; 474 475 /** 476 * Which uses have been started, so are allowed to run code. 477 */ 478 final SparseArray<UserStartedState> mStartedUsers = new SparseArray<UserStartedState>(); 479 480 /** 481 * LRU list of history of current users. Most recently current is at the end. 482 */ 483 final ArrayList<Integer> mUserLru = new ArrayList<Integer>(); 484 485 /** 486 * Constant array of the users that are currently started. 487 */ 488 int[] mStartedUserArray = new int[] { 0 }; 489 490 /** 491 * Registered observers of the user switching mechanics. 492 */ 493 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers 494 = new RemoteCallbackList<IUserSwitchObserver>(); 495 496 /** 497 * Currently active user switch. 498 */ 499 Object mCurUserSwitchCallback; 500 501 /** 502 * Packages that the user has asked to have run in screen size 503 * compatibility mode instead of filling the screen. 504 */ 505 final CompatModePackages mCompatModePackages; 506 507 /** 508 * Set of PendingResultRecord objects that are currently active. 509 */ 510 final HashSet mPendingResultRecords = new HashSet(); 511 512 /** 513 * Set of IntentSenderRecord objects that are currently active. 514 */ 515 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords 516 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>(); 517 518 /** 519 * Fingerprints (hashCode()) of stack traces that we've 520 * already logged DropBox entries for. Guarded by itself. If 521 * something (rogue user app) forces this over 522 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 523 */ 524 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 525 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 526 527 /** 528 * Strict Mode background batched logging state. 529 * 530 * The string buffer is guarded by itself, and its lock is also 531 * used to determine if another batched write is already 532 * in-flight. 533 */ 534 private final StringBuilder mStrictModeBuffer = new StringBuilder(); 535 536 /** 537 * Keeps track of all IIntentReceivers that have been registered for 538 * broadcasts. Hash keys are the receiver IBinder, hash value is 539 * a ReceiverList. 540 */ 541 final HashMap mRegisteredReceivers = new HashMap(); 542 543 /** 544 * Resolver for broadcast intents to registered receivers. 545 * Holds BroadcastFilter (subclass of IntentFilter). 546 */ 547 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 548 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 549 @Override 550 protected boolean allowFilterResult( 551 BroadcastFilter filter, List<BroadcastFilter> dest) { 552 IBinder target = filter.receiverList.receiver.asBinder(); 553 for (int i=dest.size()-1; i>=0; i--) { 554 if (dest.get(i).receiverList.receiver.asBinder() == target) { 555 return false; 556 } 557 } 558 return true; 559 } 560 561 @Override 562 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 563 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 564 || userId == filter.owningUserId) { 565 return super.newResult(filter, match, userId); 566 } 567 return null; 568 } 569 570 @Override 571 protected BroadcastFilter[] newArray(int size) { 572 return new BroadcastFilter[size]; 573 } 574 575 @Override 576 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 577 return packageName.equals(filter.packageName); 578 } 579 }; 580 581 /** 582 * State of all active sticky broadcasts per user. Keys are the action of the 583 * sticky Intent, values are an ArrayList of all broadcasted intents with 584 * that action (which should usually be one). The SparseArray is keyed 585 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 586 * for stickies that are sent to all users. 587 */ 588 final SparseArray<HashMap<String, ArrayList<Intent>>> mStickyBroadcasts = 589 new SparseArray<HashMap<String, ArrayList<Intent>>>(); 590 591 final ActiveServices mServices; 592 593 /** 594 * Backup/restore process management 595 */ 596 String mBackupAppName = null; 597 BackupRecord mBackupTarget = null; 598 599 /** 600 * List of PendingThumbnailsRecord objects of clients who are still 601 * waiting to receive all of the thumbnails for a task. 602 */ 603 final ArrayList mPendingThumbnails = new ArrayList(); 604 605 /** 606 * List of HistoryRecord objects that have been finished and must 607 * still report back to a pending thumbnail receiver. 608 */ 609 final ArrayList mCancelledThumbnails = new ArrayList(); 610 611 final ProviderMap mProviderMap; 612 613 /** 614 * List of content providers who have clients waiting for them. The 615 * application is currently being launched and the provider will be 616 * removed from this list once it is published. 617 */ 618 final ArrayList<ContentProviderRecord> mLaunchingProviders 619 = new ArrayList<ContentProviderRecord>(); 620 621 /** 622 * Global set of specific Uri permissions that have been granted. 623 */ 624 final private SparseArray<HashMap<Uri, UriPermission>> mGrantedUriPermissions 625 = new SparseArray<HashMap<Uri, UriPermission>>(); 626 627 CoreSettingsObserver mCoreSettingsObserver; 628 629 /** 630 * Thread-local storage used to carry caller permissions over through 631 * indirect content-provider access. 632 */ 633 private class Identity { 634 public int pid; 635 public int uid; 636 637 Identity(int _pid, int _uid) { 638 pid = _pid; 639 uid = _uid; 640 } 641 } 642 643 private static ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>(); 644 645 /** 646 * All information we have collected about the runtime performance of 647 * any user id that can impact battery performance. 648 */ 649 final BatteryStatsService mBatteryStatsService; 650 651 /** 652 * Information about component usage 653 */ 654 final UsageStatsService mUsageStatsService; 655 656 /** 657 * Information about and control over application operations 658 */ 659 final AppOpsService mAppOpsService; 660 661 /** 662 * Current configuration information. HistoryRecord objects are given 663 * a reference to this object to indicate which configuration they are 664 * currently running in, so this object must be kept immutable. 665 */ 666 Configuration mConfiguration = new Configuration(); 667 668 /** 669 * Current sequencing integer of the configuration, for skipping old 670 * configurations. 671 */ 672 int mConfigurationSeq = 0; 673 674 /** 675 * Hardware-reported OpenGLES version. 676 */ 677 final int GL_ES_VERSION; 678 679 /** 680 * List of initialization arguments to pass to all processes when binding applications to them. 681 * For example, references to the commonly used services. 682 */ 683 HashMap<String, IBinder> mAppBindArgs; 684 685 /** 686 * Temporary to avoid allocations. Protected by main lock. 687 */ 688 final StringBuilder mStringBuilder = new StringBuilder(256); 689 690 /** 691 * Used to control how we initialize the service. 692 */ 693 boolean mStartRunning = false; 694 ComponentName mTopComponent; 695 String mTopAction; 696 String mTopData; 697 boolean mProcessesReady = false; 698 boolean mSystemReady = false; 699 boolean mBooting = false; 700 boolean mWaitingUpdate = false; 701 boolean mDidUpdate = false; 702 boolean mOnBattery = false; 703 boolean mLaunchWarningShown = false; 704 705 Context mContext; 706 707 int mFactoryTest; 708 709 boolean mCheckedForSetup; 710 711 /** 712 * The time at which we will allow normal application switches again, 713 * after a call to {@link #stopAppSwitches()}. 714 */ 715 long mAppSwitchesAllowedTime; 716 717 /** 718 * This is set to true after the first switch after mAppSwitchesAllowedTime 719 * is set; any switches after that will clear the time. 720 */ 721 boolean mDidAppSwitch; 722 723 /** 724 * Last time (in realtime) at which we checked for power usage. 725 */ 726 long mLastPowerCheckRealtime; 727 728 /** 729 * Last time (in uptime) at which we checked for power usage. 730 */ 731 long mLastPowerCheckUptime; 732 733 /** 734 * Set while we are wanting to sleep, to prevent any 735 * activities from being started/resumed. 736 */ 737 boolean mSleeping = false; 738 739 /** 740 * State of external calls telling us if the device is asleep. 741 */ 742 boolean mWentToSleep = false; 743 744 /** 745 * State of external call telling us if the lock screen is shown. 746 */ 747 boolean mLockScreenShown = false; 748 749 /** 750 * Set if we are shutting down the system, similar to sleeping. 751 */ 752 boolean mShuttingDown = false; 753 754 /** 755 * Task identifier that activities are currently being started 756 * in. Incremented each time a new task is created. 757 * todo: Replace this with a TokenSpace class that generates non-repeating 758 * integers that won't wrap. 759 */ 760 int mCurTask = 1; 761 762 /** 763 * Current sequence id for oom_adj computation traversal. 764 */ 765 int mAdjSeq = 0; 766 767 /** 768 * Current sequence id for process LRU updating. 769 */ 770 int mLruSeq = 0; 771 772 /** 773 * Keep track of the non-hidden/empty process we last found, to help 774 * determine how to distribute hidden/empty processes next time. 775 */ 776 int mNumNonHiddenProcs = 0; 777 778 /** 779 * Keep track of the number of hidden procs, to balance oom adj 780 * distribution between those and empty procs. 781 */ 782 int mNumHiddenProcs = 0; 783 784 /** 785 * Keep track of the number of service processes we last found, to 786 * determine on the next iteration which should be B services. 787 */ 788 int mNumServiceProcs = 0; 789 int mNewNumServiceProcs = 0; 790 791 /** 792 * System monitoring: number of processes that died since the last 793 * N procs were started. 794 */ 795 int[] mProcDeaths = new int[20]; 796 797 /** 798 * This is set if we had to do a delayed dexopt of an app before launching 799 * it, to increasing the ANR timeouts in that case. 800 */ 801 boolean mDidDexOpt; 802 803 String mDebugApp = null; 804 boolean mWaitForDebugger = false; 805 boolean mDebugTransient = false; 806 String mOrigDebugApp = null; 807 boolean mOrigWaitForDebugger = false; 808 boolean mAlwaysFinishActivities = false; 809 IActivityController mController = null; 810 String mProfileApp = null; 811 ProcessRecord mProfileProc = null; 812 String mProfileFile; 813 ParcelFileDescriptor mProfileFd; 814 int mProfileType = 0; 815 boolean mAutoStopProfiler = false; 816 String mOpenGlTraceApp = null; 817 818 static class ProcessChangeItem { 819 static final int CHANGE_ACTIVITIES = 1<<0; 820 static final int CHANGE_IMPORTANCE= 1<<1; 821 int changes; 822 int uid; 823 int pid; 824 int importance; 825 boolean foregroundActivities; 826 } 827 828 final RemoteCallbackList<IProcessObserver> mProcessObservers 829 = new RemoteCallbackList<IProcessObserver>(); 830 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5]; 831 832 final ArrayList<ProcessChangeItem> mPendingProcessChanges 833 = new ArrayList<ProcessChangeItem>(); 834 final ArrayList<ProcessChangeItem> mAvailProcessChanges 835 = new ArrayList<ProcessChangeItem>(); 836 837 /** 838 * Runtime statistics collection thread. This object's lock is used to 839 * protect all related state. 840 */ 841 final Thread mProcessStatsThread; 842 843 /** 844 * Used to collect process stats when showing not responding dialog. 845 * Protected by mProcessStatsThread. 846 */ 847 final ProcessStats mProcessStats = new ProcessStats( 848 MONITOR_THREAD_CPU_USAGE); 849 final AtomicLong mLastCpuTime = new AtomicLong(0); 850 final AtomicBoolean mProcessStatsMutexFree = new AtomicBoolean(true); 851 852 long mLastWriteTime = 0; 853 854 /** 855 * Used to retain an update lock when the foreground activity is in 856 * immersive mode. 857 */ 858 final UpdateLock mUpdateLock = new UpdateLock("immersive"); 859 860 /** 861 * Set to true after the system has finished booting. 862 */ 863 boolean mBooted = false; 864 865 int mProcessLimit = ProcessList.MAX_HIDDEN_APPS; 866 int mProcessLimitOverride = -1; 867 868 WindowManagerService mWindowManager; 869 870 static ActivityManagerService mSelf; 871 static ActivityThread mSystemThread; 872 873 private int mCurrentUserId = 0; 874 private int[] mCurrentUserArray = new int[] { 0 }; 875 private UserManagerService mUserManager; 876 877 private final class AppDeathRecipient implements IBinder.DeathRecipient { 878 final ProcessRecord mApp; 879 final int mPid; 880 final IApplicationThread mAppThread; 881 882 AppDeathRecipient(ProcessRecord app, int pid, 883 IApplicationThread thread) { 884 if (localLOGV) Slog.v( 885 TAG, "New death recipient " + this 886 + " for thread " + thread.asBinder()); 887 mApp = app; 888 mPid = pid; 889 mAppThread = thread; 890 } 891 892 public void binderDied() { 893 if (localLOGV) Slog.v( 894 TAG, "Death received in " + this 895 + " for thread " + mAppThread.asBinder()); 896 synchronized(ActivityManagerService.this) { 897 appDiedLocked(mApp, mPid, mAppThread); 898 } 899 } 900 } 901 902 static final int SHOW_ERROR_MSG = 1; 903 static final int SHOW_NOT_RESPONDING_MSG = 2; 904 static final int SHOW_FACTORY_ERROR_MSG = 3; 905 static final int UPDATE_CONFIGURATION_MSG = 4; 906 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 907 static final int WAIT_FOR_DEBUGGER_MSG = 6; 908 static final int SERVICE_TIMEOUT_MSG = 12; 909 static final int UPDATE_TIME_ZONE = 13; 910 static final int SHOW_UID_ERROR_MSG = 14; 911 static final int IM_FEELING_LUCKY_MSG = 15; 912 static final int PROC_START_TIMEOUT_MSG = 20; 913 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21; 914 static final int KILL_APPLICATION_MSG = 22; 915 static final int FINALIZE_PENDING_INTENT_MSG = 23; 916 static final int POST_HEAVY_NOTIFICATION_MSG = 24; 917 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25; 918 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26; 919 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27; 920 static final int CLEAR_DNS_CACHE = 28; 921 static final int UPDATE_HTTP_PROXY = 29; 922 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30; 923 static final int DISPATCH_PROCESSES_CHANGED = 31; 924 static final int DISPATCH_PROCESS_DIED = 32; 925 static final int REPORT_MEM_USAGE = 33; 926 static final int REPORT_USER_SWITCH_MSG = 34; 927 static final int CONTINUE_USER_SWITCH_MSG = 35; 928 static final int USER_SWITCH_TIMEOUT_MSG = 36; 929 static final int IMMERSIVE_MODE_LOCK_MSG = 37; 930 931 static final int FIRST_ACTIVITY_STACK_MSG = 100; 932 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 933 static final int FIRST_COMPAT_MODE_MSG = 300; 934 935 AlertDialog mUidAlert; 936 CompatModeDialog mCompatModeDialog; 937 long mLastMemUsageReportTime = 0; 938 939 /** 940 * Flag whether the current user is a "monkey", i.e. whether 941 * the UI is driven by a UI automation tool. 942 */ 943 private boolean mUserIsMonkey; 944 945 final Handler mHandler = new Handler() { 946 //public Handler() { 947 // if (localLOGV) Slog.v(TAG, "Handler started!"); 948 //} 949 950 public void handleMessage(Message msg) { 951 switch (msg.what) { 952 case SHOW_ERROR_MSG: { 953 HashMap data = (HashMap) msg.obj; 954 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 955 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 956 synchronized (ActivityManagerService.this) { 957 ProcessRecord proc = (ProcessRecord)data.get("app"); 958 AppErrorResult res = (AppErrorResult) data.get("result"); 959 if (proc != null && proc.crashDialog != null) { 960 Slog.e(TAG, "App already has crash dialog: " + proc); 961 if (res != null) { 962 res.set(0); 963 } 964 return; 965 } 966 if (!showBackground && UserHandle.getAppId(proc.uid) 967 >= Process.FIRST_APPLICATION_UID && proc.userId != mCurrentUserId 968 && proc.pid != MY_PID) { 969 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background"); 970 if (res != null) { 971 res.set(0); 972 } 973 return; 974 } 975 if (mShowDialogs && !mSleeping && !mShuttingDown) { 976 Dialog d = new AppErrorDialog(mContext, 977 ActivityManagerService.this, res, proc); 978 d.show(); 979 proc.crashDialog = d; 980 } else { 981 // The device is asleep, so just pretend that the user 982 // saw a crash dialog and hit "force quit". 983 if (res != null) { 984 res.set(0); 985 } 986 } 987 } 988 989 ensureBootCompleted(); 990 } break; 991 case SHOW_NOT_RESPONDING_MSG: { 992 synchronized (ActivityManagerService.this) { 993 HashMap data = (HashMap) msg.obj; 994 ProcessRecord proc = (ProcessRecord)data.get("app"); 995 if (proc != null && proc.anrDialog != null) { 996 Slog.e(TAG, "App already has anr dialog: " + proc); 997 return; 998 } 999 1000 Intent intent = new Intent("android.intent.action.ANR"); 1001 if (!mProcessesReady) { 1002 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 1003 | Intent.FLAG_RECEIVER_FOREGROUND); 1004 } 1005 broadcastIntentLocked(null, null, intent, 1006 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 1007 false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */); 1008 1009 if (mShowDialogs) { 1010 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this, 1011 mContext, proc, (ActivityRecord)data.get("activity"), 1012 msg.arg1 != 0); 1013 d.show(); 1014 proc.anrDialog = d; 1015 } else { 1016 // Just kill the app if there is no dialog to be shown. 1017 killAppAtUsersRequest(proc, null); 1018 } 1019 } 1020 1021 ensureBootCompleted(); 1022 } break; 1023 case SHOW_STRICT_MODE_VIOLATION_MSG: { 1024 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1025 synchronized (ActivityManagerService.this) { 1026 ProcessRecord proc = (ProcessRecord) data.get("app"); 1027 if (proc == null) { 1028 Slog.e(TAG, "App not found when showing strict mode dialog."); 1029 break; 1030 } 1031 if (proc.crashDialog != null) { 1032 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1033 return; 1034 } 1035 AppErrorResult res = (AppErrorResult) data.get("result"); 1036 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1037 Dialog d = new StrictModeViolationDialog(mContext, 1038 ActivityManagerService.this, res, proc); 1039 d.show(); 1040 proc.crashDialog = d; 1041 } else { 1042 // The device is asleep, so just pretend that the user 1043 // saw a crash dialog and hit "force quit". 1044 res.set(0); 1045 } 1046 } 1047 ensureBootCompleted(); 1048 } break; 1049 case SHOW_FACTORY_ERROR_MSG: { 1050 Dialog d = new FactoryErrorDialog( 1051 mContext, msg.getData().getCharSequence("msg")); 1052 d.show(); 1053 ensureBootCompleted(); 1054 } break; 1055 case UPDATE_CONFIGURATION_MSG: { 1056 final ContentResolver resolver = mContext.getContentResolver(); 1057 Settings.System.putConfiguration(resolver, (Configuration)msg.obj); 1058 } break; 1059 case GC_BACKGROUND_PROCESSES_MSG: { 1060 synchronized (ActivityManagerService.this) { 1061 performAppGcsIfAppropriateLocked(); 1062 } 1063 } break; 1064 case WAIT_FOR_DEBUGGER_MSG: { 1065 synchronized (ActivityManagerService.this) { 1066 ProcessRecord app = (ProcessRecord)msg.obj; 1067 if (msg.arg1 != 0) { 1068 if (!app.waitedForDebugger) { 1069 Dialog d = new AppWaitingForDebuggerDialog( 1070 ActivityManagerService.this, 1071 mContext, app); 1072 app.waitDialog = d; 1073 app.waitedForDebugger = true; 1074 d.show(); 1075 } 1076 } else { 1077 if (app.waitDialog != null) { 1078 app.waitDialog.dismiss(); 1079 app.waitDialog = null; 1080 } 1081 } 1082 } 1083 } break; 1084 case SERVICE_TIMEOUT_MSG: { 1085 if (mDidDexOpt) { 1086 mDidDexOpt = false; 1087 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG); 1088 nmsg.obj = msg.obj; 1089 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT); 1090 return; 1091 } 1092 mServices.serviceTimeout((ProcessRecord)msg.obj); 1093 } break; 1094 case UPDATE_TIME_ZONE: { 1095 synchronized (ActivityManagerService.this) { 1096 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1097 ProcessRecord r = mLruProcesses.get(i); 1098 if (r.thread != null) { 1099 try { 1100 r.thread.updateTimeZone(); 1101 } catch (RemoteException ex) { 1102 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 1103 } 1104 } 1105 } 1106 } 1107 } break; 1108 case CLEAR_DNS_CACHE: { 1109 synchronized (ActivityManagerService.this) { 1110 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1111 ProcessRecord r = mLruProcesses.get(i); 1112 if (r.thread != null) { 1113 try { 1114 r.thread.clearDnsCache(); 1115 } catch (RemoteException ex) { 1116 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 1117 } 1118 } 1119 } 1120 } 1121 } break; 1122 case UPDATE_HTTP_PROXY: { 1123 ProxyProperties proxy = (ProxyProperties)msg.obj; 1124 String host = ""; 1125 String port = ""; 1126 String exclList = ""; 1127 if (proxy != null) { 1128 host = proxy.getHost(); 1129 port = Integer.toString(proxy.getPort()); 1130 exclList = proxy.getExclusionList(); 1131 } 1132 synchronized (ActivityManagerService.this) { 1133 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1134 ProcessRecord r = mLruProcesses.get(i); 1135 if (r.thread != null) { 1136 try { 1137 r.thread.setHttpProxy(host, port, exclList); 1138 } catch (RemoteException ex) { 1139 Slog.w(TAG, "Failed to update http proxy for: " + 1140 r.info.processName); 1141 } 1142 } 1143 } 1144 } 1145 } break; 1146 case SHOW_UID_ERROR_MSG: { 1147 String title = "System UIDs Inconsistent"; 1148 String text = "UIDs on the system are inconsistent, you need to wipe your" 1149 + " data partition or your device will be unstable."; 1150 Log.e(TAG, title + ": " + text); 1151 if (mShowDialogs) { 1152 // XXX This is a temporary dialog, no need to localize. 1153 AlertDialog d = new BaseErrorDialog(mContext); 1154 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1155 d.setCancelable(false); 1156 d.setTitle(title); 1157 d.setMessage(text); 1158 d.setButton(DialogInterface.BUTTON_POSITIVE, "I'm Feeling Lucky", 1159 mHandler.obtainMessage(IM_FEELING_LUCKY_MSG)); 1160 mUidAlert = d; 1161 d.show(); 1162 } 1163 } break; 1164 case IM_FEELING_LUCKY_MSG: { 1165 if (mUidAlert != null) { 1166 mUidAlert.dismiss(); 1167 mUidAlert = null; 1168 } 1169 } break; 1170 case PROC_START_TIMEOUT_MSG: { 1171 if (mDidDexOpt) { 1172 mDidDexOpt = false; 1173 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 1174 nmsg.obj = msg.obj; 1175 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT); 1176 return; 1177 } 1178 ProcessRecord app = (ProcessRecord)msg.obj; 1179 synchronized (ActivityManagerService.this) { 1180 processStartTimedOutLocked(app); 1181 } 1182 } break; 1183 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: { 1184 synchronized (ActivityManagerService.this) { 1185 doPendingActivityLaunchesLocked(true); 1186 } 1187 } break; 1188 case KILL_APPLICATION_MSG: { 1189 synchronized (ActivityManagerService.this) { 1190 int appid = msg.arg1; 1191 boolean restart = (msg.arg2 == 1); 1192 String pkg = (String) msg.obj; 1193 forceStopPackageLocked(pkg, appid, restart, false, true, false, 1194 UserHandle.USER_ALL); 1195 } 1196 } break; 1197 case FINALIZE_PENDING_INTENT_MSG: { 1198 ((PendingIntentRecord)msg.obj).completeFinalize(); 1199 } break; 1200 case POST_HEAVY_NOTIFICATION_MSG: { 1201 INotificationManager inm = NotificationManager.getService(); 1202 if (inm == null) { 1203 return; 1204 } 1205 1206 ActivityRecord root = (ActivityRecord)msg.obj; 1207 ProcessRecord process = root.app; 1208 if (process == null) { 1209 return; 1210 } 1211 1212 try { 1213 Context context = mContext.createPackageContext(process.info.packageName, 0); 1214 String text = mContext.getString(R.string.heavy_weight_notification, 1215 context.getApplicationInfo().loadLabel(context.getPackageManager())); 1216 Notification notification = new Notification(); 1217 notification.icon = com.android.internal.R.drawable.stat_sys_adb; //context.getApplicationInfo().icon; 1218 notification.when = 0; 1219 notification.flags = Notification.FLAG_ONGOING_EVENT; 1220 notification.tickerText = text; 1221 notification.defaults = 0; // please be quiet 1222 notification.sound = null; 1223 notification.vibrate = null; 1224 notification.setLatestEventInfo(context, text, 1225 mContext.getText(R.string.heavy_weight_notification_detail), 1226 PendingIntent.getActivityAsUser(mContext, 0, root.intent, 1227 PendingIntent.FLAG_CANCEL_CURRENT, null, 1228 new UserHandle(root.userId))); 1229 1230 try { 1231 int[] outId = new int[1]; 1232 inm.enqueueNotificationWithTag("android", "android", null, 1233 R.string.heavy_weight_notification, 1234 notification, outId, root.userId); 1235 } catch (RuntimeException e) { 1236 Slog.w(ActivityManagerService.TAG, 1237 "Error showing notification for heavy-weight app", e); 1238 } catch (RemoteException e) { 1239 } 1240 } catch (NameNotFoundException e) { 1241 Slog.w(TAG, "Unable to create context for heavy notification", e); 1242 } 1243 } break; 1244 case CANCEL_HEAVY_NOTIFICATION_MSG: { 1245 INotificationManager inm = NotificationManager.getService(); 1246 if (inm == null) { 1247 return; 1248 } 1249 try { 1250 inm.cancelNotificationWithTag("android", null, 1251 R.string.heavy_weight_notification, msg.arg1); 1252 } catch (RuntimeException e) { 1253 Slog.w(ActivityManagerService.TAG, 1254 "Error canceling notification for service", e); 1255 } catch (RemoteException e) { 1256 } 1257 } break; 1258 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: { 1259 synchronized (ActivityManagerService.this) { 1260 checkExcessivePowerUsageLocked(true); 1261 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1262 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1263 sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 1264 } 1265 } break; 1266 case SHOW_COMPAT_MODE_DIALOG_MSG: { 1267 synchronized (ActivityManagerService.this) { 1268 ActivityRecord ar = (ActivityRecord)msg.obj; 1269 if (mCompatModeDialog != null) { 1270 if (mCompatModeDialog.mAppInfo.packageName.equals( 1271 ar.info.applicationInfo.packageName)) { 1272 return; 1273 } 1274 mCompatModeDialog.dismiss(); 1275 mCompatModeDialog = null; 1276 } 1277 if (ar != null && false) { 1278 if (mCompatModePackages.getPackageAskCompatModeLocked( 1279 ar.packageName)) { 1280 int mode = mCompatModePackages.computeCompatModeLocked( 1281 ar.info.applicationInfo); 1282 if (mode == ActivityManager.COMPAT_MODE_DISABLED 1283 || mode == ActivityManager.COMPAT_MODE_ENABLED) { 1284 mCompatModeDialog = new CompatModeDialog( 1285 ActivityManagerService.this, mContext, 1286 ar.info.applicationInfo); 1287 mCompatModeDialog.show(); 1288 } 1289 } 1290 } 1291 } 1292 break; 1293 } 1294 case DISPATCH_PROCESSES_CHANGED: { 1295 dispatchProcessesChanged(); 1296 break; 1297 } 1298 case DISPATCH_PROCESS_DIED: { 1299 final int pid = msg.arg1; 1300 final int uid = msg.arg2; 1301 dispatchProcessDied(pid, uid); 1302 break; 1303 } 1304 case REPORT_MEM_USAGE: { 1305 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 1306 if (!isDebuggable) { 1307 return; 1308 } 1309 synchronized (ActivityManagerService.this) { 1310 long now = SystemClock.uptimeMillis(); 1311 if (now < (mLastMemUsageReportTime+5*60*1000)) { 1312 // Don't report more than every 5 minutes to somewhat 1313 // avoid spamming. 1314 return; 1315 } 1316 mLastMemUsageReportTime = now; 1317 } 1318 Thread thread = new Thread() { 1319 @Override public void run() { 1320 StringBuilder dropBuilder = new StringBuilder(1024); 1321 StringBuilder logBuilder = new StringBuilder(1024); 1322 StringWriter oomSw = new StringWriter(); 1323 PrintWriter oomPw = new PrintWriter(oomSw); 1324 StringWriter catSw = new StringWriter(); 1325 PrintWriter catPw = new PrintWriter(catSw); 1326 String[] emptyArgs = new String[] { }; 1327 StringBuilder tag = new StringBuilder(128); 1328 StringBuilder stack = new StringBuilder(128); 1329 tag.append("Low on memory -- "); 1330 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw, 1331 tag, stack); 1332 dropBuilder.append(stack); 1333 dropBuilder.append('\n'); 1334 dropBuilder.append('\n'); 1335 String oomString = oomSw.toString(); 1336 dropBuilder.append(oomString); 1337 dropBuilder.append('\n'); 1338 logBuilder.append(oomString); 1339 try { 1340 java.lang.Process proc = Runtime.getRuntime().exec(new String[] { 1341 "procrank", }); 1342 final InputStreamReader converter = new InputStreamReader( 1343 proc.getInputStream()); 1344 BufferedReader in = new BufferedReader(converter); 1345 String line; 1346 while (true) { 1347 line = in.readLine(); 1348 if (line == null) { 1349 break; 1350 } 1351 if (line.length() > 0) { 1352 logBuilder.append(line); 1353 logBuilder.append('\n'); 1354 } 1355 dropBuilder.append(line); 1356 dropBuilder.append('\n'); 1357 } 1358 converter.close(); 1359 } catch (IOException e) { 1360 } 1361 synchronized (ActivityManagerService.this) { 1362 catPw.println(); 1363 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null); 1364 catPw.println(); 1365 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0, 1366 false, false, null); 1367 catPw.println(); 1368 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null); 1369 } 1370 dropBuilder.append(catSw.toString()); 1371 addErrorToDropBox("lowmem", null, "system_server", null, 1372 null, tag.toString(), dropBuilder.toString(), null, null); 1373 Slog.i(TAG, logBuilder.toString()); 1374 synchronized (ActivityManagerService.this) { 1375 long now = SystemClock.uptimeMillis(); 1376 if (mLastMemUsageReportTime < now) { 1377 mLastMemUsageReportTime = now; 1378 } 1379 } 1380 } 1381 }; 1382 thread.start(); 1383 break; 1384 } 1385 case REPORT_USER_SWITCH_MSG: { 1386 dispatchUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2); 1387 break; 1388 } 1389 case CONTINUE_USER_SWITCH_MSG: { 1390 continueUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2); 1391 break; 1392 } 1393 case USER_SWITCH_TIMEOUT_MSG: { 1394 timeoutUserSwitch((UserStartedState)msg.obj, msg.arg1, msg.arg2); 1395 break; 1396 } 1397 case IMMERSIVE_MODE_LOCK_MSG: { 1398 final boolean nextState = (msg.arg1 != 0); 1399 if (mUpdateLock.isHeld() != nextState) { 1400 if (DEBUG_IMMERSIVE) { 1401 final ActivityRecord r = (ActivityRecord) msg.obj; 1402 Slog.d(TAG, "Applying new update lock state '" + nextState + "' for " + r); 1403 } 1404 if (nextState) { 1405 mUpdateLock.acquire(); 1406 } else { 1407 mUpdateLock.release(); 1408 } 1409 } 1410 break; 1411 } 1412 } 1413 } 1414 }; 1415 1416 public static void setSystemProcess() { 1417 try { 1418 ActivityManagerService m = mSelf; 1419 1420 ServiceManager.addService("activity", m, true); 1421 ServiceManager.addService("meminfo", new MemBinder(m)); 1422 ServiceManager.addService("gfxinfo", new GraphicsBinder(m)); 1423 ServiceManager.addService("dbinfo", new DbBinder(m)); 1424 if (MONITOR_CPU_USAGE) { 1425 ServiceManager.addService("cpuinfo", new CpuBinder(m)); 1426 } 1427 ServiceManager.addService("permission", new PermissionController(m)); 1428 1429 ApplicationInfo info = 1430 mSelf.mContext.getPackageManager().getApplicationInfo( 1431 "android", STOCK_PM_FLAGS); 1432 mSystemThread.installSystemApplicationInfo(info); 1433 1434 synchronized (mSelf) { 1435 ProcessRecord app = mSelf.newProcessRecordLocked( 1436 mSystemThread.getApplicationThread(), info, 1437 info.processName, false); 1438 app.persistent = true; 1439 app.pid = MY_PID; 1440 app.maxAdj = ProcessList.SYSTEM_ADJ; 1441 mSelf.mProcessNames.put(app.processName, app.uid, app); 1442 synchronized (mSelf.mPidsSelfLocked) { 1443 mSelf.mPidsSelfLocked.put(app.pid, app); 1444 } 1445 mSelf.updateLruProcessLocked(app, true); 1446 } 1447 } catch (PackageManager.NameNotFoundException e) { 1448 throw new RuntimeException( 1449 "Unable to find android system package", e); 1450 } 1451 } 1452 1453 public void setWindowManager(WindowManagerService wm) { 1454 mWindowManager = wm; 1455 } 1456 1457 public void startObservingNativeCrashes() { 1458 final NativeCrashListener ncl = new NativeCrashListener(); 1459 ncl.start(); 1460 } 1461 1462 public static final Context main(int factoryTest) { 1463 AThread thr = new AThread(); 1464 thr.start(); 1465 1466 synchronized (thr) { 1467 while (thr.mService == null) { 1468 try { 1469 thr.wait(); 1470 } catch (InterruptedException e) { 1471 } 1472 } 1473 } 1474 1475 ActivityManagerService m = thr.mService; 1476 mSelf = m; 1477 ActivityThread at = ActivityThread.systemMain(); 1478 mSystemThread = at; 1479 Context context = at.getSystemContext(); 1480 context.setTheme(android.R.style.Theme_Holo); 1481 m.mContext = context; 1482 m.mFactoryTest = factoryTest; 1483 m.mMainStack = new ActivityStack(m, context, true, thr.mLooper); 1484 m.mIntentFirewall = new IntentFirewall(m.new IntentFirewallInterface()); 1485 1486 m.mBatteryStatsService.publish(context); 1487 m.mUsageStatsService.publish(context); 1488 m.mAppOpsService.publish(context); 1489 1490 synchronized (thr) { 1491 thr.mReady = true; 1492 thr.notifyAll(); 1493 } 1494 1495 m.startRunning(null, null, null, null); 1496 1497 return context; 1498 } 1499 1500 public static ActivityManagerService self() { 1501 return mSelf; 1502 } 1503 1504 static class AThread extends Thread { 1505 ActivityManagerService mService; 1506 Looper mLooper; 1507 boolean mReady = false; 1508 1509 public AThread() { 1510 super("ActivityManager"); 1511 } 1512 1513 public void run() { 1514 Looper.prepare(); 1515 1516 android.os.Process.setThreadPriority( 1517 android.os.Process.THREAD_PRIORITY_FOREGROUND); 1518 android.os.Process.setCanSelfBackground(false); 1519 1520 ActivityManagerService m = new ActivityManagerService(); 1521 1522 synchronized (this) { 1523 mService = m; 1524 mLooper = Looper.myLooper(); 1525 notifyAll(); 1526 } 1527 1528 synchronized (this) { 1529 while (!mReady) { 1530 try { 1531 wait(); 1532 } catch (InterruptedException e) { 1533 } 1534 } 1535 } 1536 1537 // For debug builds, log event loop stalls to dropbox for analysis. 1538 if (StrictMode.conditionallyEnableDebugLogging()) { 1539 Slog.i(TAG, "Enabled StrictMode logging for AThread's Looper"); 1540 } 1541 1542 Looper.loop(); 1543 } 1544 } 1545 1546 static class MemBinder extends Binder { 1547 ActivityManagerService mActivityManagerService; 1548 MemBinder(ActivityManagerService activityManagerService) { 1549 mActivityManagerService = activityManagerService; 1550 } 1551 1552 @Override 1553 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1554 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1555 != PackageManager.PERMISSION_GRANTED) { 1556 pw.println("Permission Denial: can't dump meminfo from from pid=" 1557 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1558 + " without permission " + android.Manifest.permission.DUMP); 1559 return; 1560 } 1561 1562 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, 1563 false, null, null, null); 1564 } 1565 } 1566 1567 static class GraphicsBinder extends Binder { 1568 ActivityManagerService mActivityManagerService; 1569 GraphicsBinder(ActivityManagerService activityManagerService) { 1570 mActivityManagerService = activityManagerService; 1571 } 1572 1573 @Override 1574 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1575 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1576 != PackageManager.PERMISSION_GRANTED) { 1577 pw.println("Permission Denial: can't dump gfxinfo from from pid=" 1578 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1579 + " without permission " + android.Manifest.permission.DUMP); 1580 return; 1581 } 1582 1583 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 1584 } 1585 } 1586 1587 static class DbBinder extends Binder { 1588 ActivityManagerService mActivityManagerService; 1589 DbBinder(ActivityManagerService activityManagerService) { 1590 mActivityManagerService = activityManagerService; 1591 } 1592 1593 @Override 1594 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1595 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1596 != PackageManager.PERMISSION_GRANTED) { 1597 pw.println("Permission Denial: can't dump dbinfo from from pid=" 1598 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1599 + " without permission " + android.Manifest.permission.DUMP); 1600 return; 1601 } 1602 1603 mActivityManagerService.dumpDbInfo(fd, pw, args); 1604 } 1605 } 1606 1607 static class CpuBinder extends Binder { 1608 ActivityManagerService mActivityManagerService; 1609 CpuBinder(ActivityManagerService activityManagerService) { 1610 mActivityManagerService = activityManagerService; 1611 } 1612 1613 @Override 1614 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 1615 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 1616 != PackageManager.PERMISSION_GRANTED) { 1617 pw.println("Permission Denial: can't dump cpuinfo from from pid=" 1618 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 1619 + " without permission " + android.Manifest.permission.DUMP); 1620 return; 1621 } 1622 1623 synchronized (mActivityManagerService.mProcessStatsThread) { 1624 pw.print(mActivityManagerService.mProcessStats.printCurrentLoad()); 1625 pw.print(mActivityManagerService.mProcessStats.printCurrentState( 1626 SystemClock.uptimeMillis())); 1627 } 1628 } 1629 } 1630 1631 private ActivityManagerService() { 1632 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 1633 1634 mFgBroadcastQueue = new BroadcastQueue(this, "foreground", BROADCAST_FG_TIMEOUT); 1635 mBgBroadcastQueue = new BroadcastQueue(this, "background", BROADCAST_BG_TIMEOUT); 1636 mBroadcastQueues[0] = mFgBroadcastQueue; 1637 mBroadcastQueues[1] = mBgBroadcastQueue; 1638 1639 mServices = new ActiveServices(this); 1640 mProviderMap = new ProviderMap(this); 1641 1642 File dataDir = Environment.getDataDirectory(); 1643 File systemDir = new File(dataDir, "system"); 1644 systemDir.mkdirs(); 1645 mBatteryStatsService = new BatteryStatsService(new File( 1646 systemDir, "batterystats.bin").toString()); 1647 mBatteryStatsService.getActiveStatistics().readLocked(); 1648 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 1649 mOnBattery = DEBUG_POWER ? true 1650 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 1651 mBatteryStatsService.getActiveStatistics().setCallback(this); 1652 1653 mUsageStatsService = new UsageStatsService(new File( 1654 systemDir, "usagestats").toString()); 1655 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml")); 1656 mHeadless = "1".equals(SystemProperties.get("ro.config.headless", "0")); 1657 1658 // User 0 is the first and only user that runs at boot. 1659 mStartedUsers.put(0, new UserStartedState(new UserHandle(0), true)); 1660 mUserLru.add(Integer.valueOf(0)); 1661 updateStartedUserArrayLocked(); 1662 1663 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", 1664 ConfigurationInfo.GL_ES_VERSION_UNDEFINED); 1665 1666 mConfiguration.setToDefaults(); 1667 mConfiguration.setLocale(Locale.getDefault()); 1668 1669 mConfigurationSeq = mConfiguration.seq = 1; 1670 mProcessStats.init(); 1671 1672 mCompatModePackages = new CompatModePackages(this, systemDir); 1673 1674 // Add ourself to the Watchdog monitors. 1675 Watchdog.getInstance().addMonitor(this); 1676 1677 mProcessStatsThread = new Thread("ProcessStats") { 1678 public void run() { 1679 while (true) { 1680 try { 1681 try { 1682 synchronized(this) { 1683 final long now = SystemClock.uptimeMillis(); 1684 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 1685 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 1686 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 1687 // + ", write delay=" + nextWriteDelay); 1688 if (nextWriteDelay < nextCpuDelay) { 1689 nextCpuDelay = nextWriteDelay; 1690 } 1691 if (nextCpuDelay > 0) { 1692 mProcessStatsMutexFree.set(true); 1693 this.wait(nextCpuDelay); 1694 } 1695 } 1696 } catch (InterruptedException e) { 1697 } 1698 updateCpuStatsNow(); 1699 } catch (Exception e) { 1700 Slog.e(TAG, "Unexpected exception collecting process stats", e); 1701 } 1702 } 1703 } 1704 }; 1705 mProcessStatsThread.start(); 1706 } 1707 1708 @Override 1709 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 1710 throws RemoteException { 1711 if (code == SYSPROPS_TRANSACTION) { 1712 // We need to tell all apps about the system property change. 1713 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 1714 synchronized(this) { 1715 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) { 1716 final int NA = apps.size(); 1717 for (int ia=0; ia<NA; ia++) { 1718 ProcessRecord app = apps.valueAt(ia); 1719 if (app.thread != null) { 1720 procs.add(app.thread.asBinder()); 1721 } 1722 } 1723 } 1724 } 1725 1726 int N = procs.size(); 1727 for (int i=0; i<N; i++) { 1728 Parcel data2 = Parcel.obtain(); 1729 try { 1730 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0); 1731 } catch (RemoteException e) { 1732 } 1733 data2.recycle(); 1734 } 1735 } 1736 try { 1737 return super.onTransact(code, data, reply, flags); 1738 } catch (RuntimeException e) { 1739 // The activity manager only throws security exceptions, so let's 1740 // log all others. 1741 if (!(e instanceof SecurityException)) { 1742 Slog.e(TAG, "Activity Manager Crash", e); 1743 } 1744 throw e; 1745 } 1746 } 1747 1748 void updateCpuStats() { 1749 final long now = SystemClock.uptimeMillis(); 1750 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 1751 return; 1752 } 1753 if (mProcessStatsMutexFree.compareAndSet(true, false)) { 1754 synchronized (mProcessStatsThread) { 1755 mProcessStatsThread.notify(); 1756 } 1757 } 1758 } 1759 1760 void updateCpuStatsNow() { 1761 synchronized (mProcessStatsThread) { 1762 mProcessStatsMutexFree.set(false); 1763 final long now = SystemClock.uptimeMillis(); 1764 boolean haveNewCpuStats = false; 1765 1766 if (MONITOR_CPU_USAGE && 1767 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 1768 mLastCpuTime.set(now); 1769 haveNewCpuStats = true; 1770 mProcessStats.update(); 1771 //Slog.i(TAG, mProcessStats.printCurrentState()); 1772 //Slog.i(TAG, "Total CPU usage: " 1773 // + mProcessStats.getTotalCpuPercent() + "%"); 1774 1775 // Slog the cpu usage if the property is set. 1776 if ("true".equals(SystemProperties.get("events.cpu"))) { 1777 int user = mProcessStats.getLastUserTime(); 1778 int system = mProcessStats.getLastSystemTime(); 1779 int iowait = mProcessStats.getLastIoWaitTime(); 1780 int irq = mProcessStats.getLastIrqTime(); 1781 int softIrq = mProcessStats.getLastSoftIrqTime(); 1782 int idle = mProcessStats.getLastIdleTime(); 1783 1784 int total = user + system + iowait + irq + softIrq + idle; 1785 if (total == 0) total = 1; 1786 1787 EventLog.writeEvent(EventLogTags.CPU, 1788 ((user+system+iowait+irq+softIrq) * 100) / total, 1789 (user * 100) / total, 1790 (system * 100) / total, 1791 (iowait * 100) / total, 1792 (irq * 100) / total, 1793 (softIrq * 100) / total); 1794 } 1795 } 1796 1797 long[] cpuSpeedTimes = mProcessStats.getLastCpuSpeedTimes(); 1798 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 1799 synchronized(bstats) { 1800 synchronized(mPidsSelfLocked) { 1801 if (haveNewCpuStats) { 1802 if (mOnBattery) { 1803 int perc = bstats.startAddingCpuLocked(); 1804 int totalUTime = 0; 1805 int totalSTime = 0; 1806 final int N = mProcessStats.countStats(); 1807 for (int i=0; i<N; i++) { 1808 ProcessStats.Stats st = mProcessStats.getStats(i); 1809 if (!st.working) { 1810 continue; 1811 } 1812 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 1813 int otherUTime = (st.rel_utime*perc)/100; 1814 int otherSTime = (st.rel_stime*perc)/100; 1815 totalUTime += otherUTime; 1816 totalSTime += otherSTime; 1817 if (pr != null) { 1818 BatteryStatsImpl.Uid.Proc ps = pr.batteryStats; 1819 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 1820 st.rel_stime-otherSTime); 1821 ps.addSpeedStepTimes(cpuSpeedTimes); 1822 pr.curCpuTime += (st.rel_utime+st.rel_stime) * 10; 1823 } else { 1824 BatteryStatsImpl.Uid.Proc ps = 1825 bstats.getProcessStatsLocked(st.name, st.pid); 1826 if (ps != null) { 1827 ps.addCpuTimeLocked(st.rel_utime-otherUTime, 1828 st.rel_stime-otherSTime); 1829 ps.addSpeedStepTimes(cpuSpeedTimes); 1830 } 1831 } 1832 } 1833 bstats.finishAddingCpuLocked(perc, totalUTime, 1834 totalSTime, cpuSpeedTimes); 1835 } 1836 } 1837 } 1838 1839 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 1840 mLastWriteTime = now; 1841 mBatteryStatsService.getActiveStatistics().writeAsyncLocked(); 1842 } 1843 } 1844 } 1845 } 1846 1847 @Override 1848 public void batteryNeedsCpuUpdate() { 1849 updateCpuStatsNow(); 1850 } 1851 1852 @Override 1853 public void batteryPowerChanged(boolean onBattery) { 1854 // When plugging in, update the CPU stats first before changing 1855 // the plug state. 1856 updateCpuStatsNow(); 1857 synchronized (this) { 1858 synchronized(mPidsSelfLocked) { 1859 mOnBattery = DEBUG_POWER ? true : onBattery; 1860 } 1861 } 1862 } 1863 1864 /** 1865 * Initialize the application bind args. These are passed to each 1866 * process when the bindApplication() IPC is sent to the process. They're 1867 * lazily setup to make sure the services are running when they're asked for. 1868 */ 1869 private HashMap<String, IBinder> getCommonServicesLocked() { 1870 if (mAppBindArgs == null) { 1871 mAppBindArgs = new HashMap<String, IBinder>(); 1872 1873 // Setup the application init args 1874 mAppBindArgs.put("package", ServiceManager.getService("package")); 1875 mAppBindArgs.put("window", ServiceManager.getService("window")); 1876 mAppBindArgs.put(Context.ALARM_SERVICE, 1877 ServiceManager.getService(Context.ALARM_SERVICE)); 1878 } 1879 return mAppBindArgs; 1880 } 1881 1882 final void setFocusedActivityLocked(ActivityRecord r) { 1883 if (mFocusedActivity != r) { 1884 mFocusedActivity = r; 1885 if (r != null) { 1886 mWindowManager.setFocusedApp(r.appToken, true); 1887 } 1888 applyUpdateLockStateLocked(r); 1889 } 1890 } 1891 1892 final void applyUpdateLockStateLocked(ActivityRecord r) { 1893 // Modifications to the UpdateLock state are done on our handler, outside 1894 // the activity manager's locks. The new state is determined based on the 1895 // state *now* of the relevant activity record. The object is passed to 1896 // the handler solely for logging detail, not to be consulted/modified. 1897 final boolean nextState = r != null && r.immersive; 1898 mHandler.sendMessage( 1899 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r)); 1900 } 1901 1902 private final void updateLruProcessInternalLocked(ProcessRecord app, int bestPos) { 1903 // put it on the LRU to keep track of when it should be exited. 1904 int lrui = mLruProcesses.indexOf(app); 1905 if (lrui >= 0) mLruProcesses.remove(lrui); 1906 1907 int i = mLruProcesses.size()-1; 1908 int skipTop = 0; 1909 1910 app.lruSeq = mLruSeq; 1911 1912 // compute the new weight for this process. 1913 app.lastActivityTime = SystemClock.uptimeMillis(); 1914 if (app.activities.size() > 0) { 1915 // If this process has activities, we more strongly want to keep 1916 // it around. 1917 app.lruWeight = app.lastActivityTime; 1918 } else if (app.pubProviders.size() > 0) { 1919 // If this process contains content providers, we want to keep 1920 // it a little more strongly. 1921 app.lruWeight = app.lastActivityTime - ProcessList.CONTENT_APP_IDLE_OFFSET; 1922 // Also don't let it kick out the first few "real" hidden processes. 1923 skipTop = ProcessList.MIN_HIDDEN_APPS; 1924 } else { 1925 // If this process doesn't have activities, we less strongly 1926 // want to keep it around, and generally want to avoid getting 1927 // in front of any very recently used activities. 1928 app.lruWeight = app.lastActivityTime - ProcessList.EMPTY_APP_IDLE_OFFSET; 1929 // Also don't let it kick out the first few "real" hidden processes. 1930 skipTop = ProcessList.MIN_HIDDEN_APPS; 1931 } 1932 1933 while (i >= 0) { 1934 ProcessRecord p = mLruProcesses.get(i); 1935 // If this app shouldn't be in front of the first N background 1936 // apps, then skip over that many that are currently hidden. 1937 if (skipTop > 0 && p.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 1938 skipTop--; 1939 } 1940 if (p.lruWeight <= app.lruWeight || i < bestPos) { 1941 mLruProcesses.add(i+1, app); 1942 break; 1943 } 1944 i--; 1945 } 1946 if (i < 0) { 1947 mLruProcesses.add(0, app); 1948 } 1949 1950 // If the app is currently using a content provider or service, 1951 // bump those processes as well. 1952 if (app.connections.size() > 0) { 1953 for (ConnectionRecord cr : app.connections) { 1954 if (cr.binding != null && cr.binding.service != null 1955 && cr.binding.service.app != null 1956 && cr.binding.service.app.lruSeq != mLruSeq) { 1957 updateLruProcessInternalLocked(cr.binding.service.app, i+1); 1958 } 1959 } 1960 } 1961 for (int j=app.conProviders.size()-1; j>=0; j--) { 1962 ContentProviderRecord cpr = app.conProviders.get(j).provider; 1963 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq) { 1964 updateLruProcessInternalLocked(cpr.proc, i+1); 1965 } 1966 } 1967 } 1968 1969 final void updateLruProcessLocked(ProcessRecord app, 1970 boolean oomAdj) { 1971 mLruSeq++; 1972 updateLruProcessInternalLocked(app, 0); 1973 1974 //Slog.i(TAG, "Putting proc to front: " + app.processName); 1975 if (oomAdj) { 1976 updateOomAdjLocked(); 1977 } 1978 } 1979 1980 final ProcessRecord getProcessRecordLocked( 1981 String processName, int uid) { 1982 if (uid == Process.SYSTEM_UID) { 1983 // The system gets to run in any process. If there are multiple 1984 // processes with the same uid, just pick the first (this 1985 // should never happen). 1986 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get( 1987 processName); 1988 if (procs == null) return null; 1989 final int N = procs.size(); 1990 for (int i = 0; i < N; i++) { 1991 if (UserHandle.isSameUser(procs.keyAt(i), uid)) return procs.valueAt(i); 1992 } 1993 } 1994 ProcessRecord proc = mProcessNames.get(processName, uid); 1995 return proc; 1996 } 1997 1998 void ensurePackageDexOpt(String packageName) { 1999 IPackageManager pm = AppGlobals.getPackageManager(); 2000 try { 2001 if (pm.performDexOpt(packageName)) { 2002 mDidDexOpt = true; 2003 } 2004 } catch (RemoteException e) { 2005 } 2006 } 2007 2008 boolean isNextTransitionForward() { 2009 int transit = mWindowManager.getPendingAppTransition(); 2010 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN 2011 || transit == AppTransition.TRANSIT_TASK_OPEN 2012 || transit == AppTransition.TRANSIT_TASK_TO_FRONT; 2013 } 2014 2015 final ProcessRecord startProcessLocked(String processName, 2016 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 2017 String hostingType, ComponentName hostingName, boolean allowWhileBooting, 2018 boolean isolated) { 2019 ProcessRecord app; 2020 if (!isolated) { 2021 app = getProcessRecordLocked(processName, info.uid); 2022 } else { 2023 // If this is an isolated process, it can't re-use an existing process. 2024 app = null; 2025 } 2026 // We don't have to do anything more if: 2027 // (1) There is an existing application record; and 2028 // (2) The caller doesn't think it is dead, OR there is no thread 2029 // object attached to it so we know it couldn't have crashed; and 2030 // (3) There is a pid assigned to it, so it is either starting or 2031 // already running. 2032 if (DEBUG_PROCESSES) Slog.v(TAG, "startProcess: name=" + processName 2033 + " app=" + app + " knownToBeDead=" + knownToBeDead 2034 + " thread=" + (app != null ? app.thread : null) 2035 + " pid=" + (app != null ? app.pid : -1)); 2036 if (app != null && app.pid > 0) { 2037 if (!knownToBeDead || app.thread == null) { 2038 // We already have the app running, or are waiting for it to 2039 // come up (we have a pid but not yet its thread), so keep it. 2040 if (DEBUG_PROCESSES) Slog.v(TAG, "App already running: " + app); 2041 // If this is a new package in the process, add the package to the list 2042 app.addPackage(info.packageName); 2043 return app; 2044 } else { 2045 // An application record is attached to a previous process, 2046 // clean it up now. 2047 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG, "App died: " + app); 2048 handleAppDiedLocked(app, true, true); 2049 } 2050 } 2051 2052 String hostingNameStr = hostingName != null 2053 ? hostingName.flattenToShortString() : null; 2054 2055 if (!isolated) { 2056 if ((intentFlags&Intent.FLAG_FROM_BACKGROUND) != 0) { 2057 // If we are in the background, then check to see if this process 2058 // is bad. If so, we will just silently fail. 2059 if (mBadProcesses.get(info.processName, info.uid) != null) { 2060 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 2061 + "/" + info.processName); 2062 return null; 2063 } 2064 } else { 2065 // When the user is explicitly starting a process, then clear its 2066 // crash count so that we won't make it bad until they see at 2067 // least one crash dialog again, and make the process good again 2068 // if it had been bad. 2069 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 2070 + "/" + info.processName); 2071 mProcessCrashTimes.remove(info.processName, info.uid); 2072 if (mBadProcesses.get(info.processName, info.uid) != null) { 2073 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, 2074 UserHandle.getUserId(info.uid), info.uid, 2075 info.processName); 2076 mBadProcesses.remove(info.processName, info.uid); 2077 if (app != null) { 2078 app.bad = false; 2079 } 2080 } 2081 } 2082 } 2083 2084 if (app == null) { 2085 app = newProcessRecordLocked(null, info, processName, isolated); 2086 if (app == null) { 2087 Slog.w(TAG, "Failed making new process record for " 2088 + processName + "/" + info.uid + " isolated=" + isolated); 2089 return null; 2090 } 2091 mProcessNames.put(processName, app.uid, app); 2092 if (isolated) { 2093 mIsolatedProcesses.put(app.uid, app); 2094 } 2095 } else { 2096 // If this is a new package in the process, add the package to the list 2097 app.addPackage(info.packageName); 2098 } 2099 2100 // If the system is not ready yet, then hold off on starting this 2101 // process until it is. 2102 if (!mProcessesReady 2103 && !isAllowedWhileBooting(info) 2104 && !allowWhileBooting) { 2105 if (!mProcessesOnHold.contains(app)) { 2106 mProcessesOnHold.add(app); 2107 } 2108 if (DEBUG_PROCESSES) Slog.v(TAG, "System not ready, putting on hold: " + app); 2109 return app; 2110 } 2111 2112 startProcessLocked(app, hostingType, hostingNameStr); 2113 return (app.pid != 0) ? app : null; 2114 } 2115 2116 boolean isAllowedWhileBooting(ApplicationInfo ai) { 2117 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 2118 } 2119 2120 private final void startProcessLocked(ProcessRecord app, 2121 String hostingType, String hostingNameStr) { 2122 if (app.pid > 0 && app.pid != MY_PID) { 2123 synchronized (mPidsSelfLocked) { 2124 mPidsSelfLocked.remove(app.pid); 2125 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 2126 } 2127 app.setPid(0); 2128 } 2129 2130 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 2131 "startProcessLocked removing on hold: " + app); 2132 mProcessesOnHold.remove(app); 2133 2134 updateCpuStats(); 2135 2136 System.arraycopy(mProcDeaths, 0, mProcDeaths, 1, mProcDeaths.length-1); 2137 mProcDeaths[0] = 0; 2138 2139 try { 2140 int uid = app.uid; 2141 2142 int[] gids = null; 2143 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE; 2144 if (!app.isolated) { 2145 int[] permGids = null; 2146 try { 2147 final PackageManager pm = mContext.getPackageManager(); 2148 permGids = pm.getPackageGids(app.info.packageName); 2149 2150 if (Environment.isExternalStorageEmulated()) { 2151 if (pm.checkPermission( 2152 android.Manifest.permission.ACCESS_ALL_EXTERNAL_STORAGE, 2153 app.info.packageName) == PERMISSION_GRANTED) { 2154 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER_ALL; 2155 } else { 2156 mountExternal = Zygote.MOUNT_EXTERNAL_MULTIUSER; 2157 } 2158 } 2159 } catch (PackageManager.NameNotFoundException e) { 2160 Slog.w(TAG, "Unable to retrieve gids", e); 2161 } 2162 2163 /* 2164 * Add shared application GID so applications can share some 2165 * resources like shared libraries 2166 */ 2167 if (permGids == null) { 2168 gids = new int[1]; 2169 } else { 2170 gids = new int[permGids.length + 1]; 2171 System.arraycopy(permGids, 0, gids, 1, permGids.length); 2172 } 2173 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid)); 2174 } 2175 if (mFactoryTest != SystemServer.FACTORY_TEST_OFF) { 2176 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL 2177 && mTopComponent != null 2178 && app.processName.equals(mTopComponent.getPackageName())) { 2179 uid = 0; 2180 } 2181 if (mFactoryTest == SystemServer.FACTORY_TEST_HIGH_LEVEL 2182 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) { 2183 uid = 0; 2184 } 2185 } 2186 int debugFlags = 0; 2187 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 2188 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER; 2189 // Also turn on CheckJNI for debuggable apps. It's quite 2190 // awkward to turn on otherwise. 2191 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 2192 } 2193 // Run the app in safe mode if its manifest requests so or the 2194 // system is booted in safe mode. 2195 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || 2196 Zygote.systemInSafeMode == true) { 2197 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 2198 } 2199 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 2200 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 2201 } 2202 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 2203 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 2204 } 2205 if ("1".equals(SystemProperties.get("debug.assert"))) { 2206 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; 2207 } 2208 2209 // Start the process. It will either succeed and return a result containing 2210 // the PID of the new process, or else throw a RuntimeException. 2211 Process.ProcessStartResult startResult = Process.start("android.app.ActivityThread", 2212 app.processName, uid, uid, gids, debugFlags, mountExternal, 2213 app.info.targetSdkVersion, app.info.seinfo, null); 2214 2215 BatteryStatsImpl bs = app.batteryStats.getBatteryStats(); 2216 synchronized (bs) { 2217 if (bs.isOnBattery()) { 2218 app.batteryStats.incStartsLocked(); 2219 } 2220 } 2221 2222 EventLog.writeEvent(EventLogTags.AM_PROC_START, 2223 UserHandle.getUserId(uid), startResult.pid, uid, 2224 app.processName, hostingType, 2225 hostingNameStr != null ? hostingNameStr : ""); 2226 2227 if (app.persistent) { 2228 Watchdog.getInstance().processStarted(app.processName, startResult.pid); 2229 } 2230 2231 StringBuilder buf = mStringBuilder; 2232 buf.setLength(0); 2233 buf.append("Start proc "); 2234 buf.append(app.processName); 2235 buf.append(" for "); 2236 buf.append(hostingType); 2237 if (hostingNameStr != null) { 2238 buf.append(" "); 2239 buf.append(hostingNameStr); 2240 } 2241 buf.append(": pid="); 2242 buf.append(startResult.pid); 2243 buf.append(" uid="); 2244 buf.append(uid); 2245 buf.append(" gids={"); 2246 if (gids != null) { 2247 for (int gi=0; gi<gids.length; gi++) { 2248 if (gi != 0) buf.append(", "); 2249 buf.append(gids[gi]); 2250 2251 } 2252 } 2253 buf.append("}"); 2254 Slog.i(TAG, buf.toString()); 2255 app.setPid(startResult.pid); 2256 app.usingWrapper = startResult.usingWrapper; 2257 app.removed = false; 2258 synchronized (mPidsSelfLocked) { 2259 this.mPidsSelfLocked.put(startResult.pid, app); 2260 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 2261 msg.obj = app; 2262 mHandler.sendMessageDelayed(msg, startResult.usingWrapper 2263 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 2264 } 2265 } catch (RuntimeException e) { 2266 // XXX do better error recovery. 2267 app.setPid(0); 2268 Slog.e(TAG, "Failure starting process " + app.processName, e); 2269 } 2270 } 2271 2272 void updateUsageStats(ActivityRecord resumedComponent, boolean resumed) { 2273 if (resumed) { 2274 mUsageStatsService.noteResumeComponent(resumedComponent.realActivity); 2275 } else { 2276 mUsageStatsService.notePauseComponent(resumedComponent.realActivity); 2277 } 2278 } 2279 2280 boolean startHomeActivityLocked(int userId) { 2281 if (mHeadless) { 2282 // Added because none of the other calls to ensureBootCompleted seem to fire 2283 // when running headless. 2284 ensureBootCompleted(); 2285 return false; 2286 } 2287 2288 if (mFactoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL 2289 && mTopAction == null) { 2290 // We are running in factory test mode, but unable to find 2291 // the factory test app, so just sit around displaying the 2292 // error message and don't try to start anything. 2293 return false; 2294 } 2295 Intent intent = new Intent( 2296 mTopAction, 2297 mTopData != null ? Uri.parse(mTopData) : null); 2298 intent.setComponent(mTopComponent); 2299 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) { 2300 intent.addCategory(Intent.CATEGORY_HOME); 2301 } 2302 ActivityInfo aInfo = 2303 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); 2304 if (aInfo != null) { 2305 intent.setComponent(new ComponentName( 2306 aInfo.applicationInfo.packageName, aInfo.name)); 2307 // Don't do this if the home app is currently being 2308 // instrumented. 2309 aInfo = new ActivityInfo(aInfo); 2310 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId); 2311 ProcessRecord app = getProcessRecordLocked(aInfo.processName, 2312 aInfo.applicationInfo.uid); 2313 if (app == null || app.instrumentationClass == null) { 2314 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 2315 mMainStack.startActivityLocked(null, intent, null, aInfo, 2316 null, null, 0, 0, 0, null, 0, null, false, null); 2317 } 2318 } 2319 2320 return true; 2321 } 2322 2323 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) { 2324 ActivityInfo ai = null; 2325 ComponentName comp = intent.getComponent(); 2326 try { 2327 if (comp != null) { 2328 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId); 2329 } else { 2330 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent( 2331 intent, 2332 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 2333 flags, userId); 2334 2335 if (info != null) { 2336 ai = info.activityInfo; 2337 } 2338 } 2339 } catch (RemoteException e) { 2340 // ignore 2341 } 2342 2343 return ai; 2344 } 2345 2346 /** 2347 * Starts the "new version setup screen" if appropriate. 2348 */ 2349 void startSetupActivityLocked() { 2350 // Only do this once per boot. 2351 if (mCheckedForSetup) { 2352 return; 2353 } 2354 2355 // We will show this screen if the current one is a different 2356 // version than the last one shown, and we are not running in 2357 // low-level factory test mode. 2358 final ContentResolver resolver = mContext.getContentResolver(); 2359 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL && 2360 Settings.Global.getInt(resolver, 2361 Settings.Global.DEVICE_PROVISIONED, 0) != 0) { 2362 mCheckedForSetup = true; 2363 2364 // See if we should be showing the platform update setup UI. 2365 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP); 2366 List<ResolveInfo> ris = mSelf.mContext.getPackageManager() 2367 .queryIntentActivities(intent, PackageManager.GET_META_DATA); 2368 2369 // We don't allow third party apps to replace this. 2370 ResolveInfo ri = null; 2371 for (int i=0; ris != null && i<ris.size(); i++) { 2372 if ((ris.get(i).activityInfo.applicationInfo.flags 2373 & ApplicationInfo.FLAG_SYSTEM) != 0) { 2374 ri = ris.get(i); 2375 break; 2376 } 2377 } 2378 2379 if (ri != null) { 2380 String vers = ri.activityInfo.metaData != null 2381 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION) 2382 : null; 2383 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) { 2384 vers = ri.activityInfo.applicationInfo.metaData.getString( 2385 Intent.METADATA_SETUP_VERSION); 2386 } 2387 String lastVers = Settings.Secure.getString( 2388 resolver, Settings.Secure.LAST_SETUP_SHOWN); 2389 if (vers != null && !vers.equals(lastVers)) { 2390 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 2391 intent.setComponent(new ComponentName( 2392 ri.activityInfo.packageName, ri.activityInfo.name)); 2393 mMainStack.startActivityLocked(null, intent, null, ri.activityInfo, 2394 null, null, 0, 0, 0, null, 0, null, false, null); 2395 } 2396 } 2397 } 2398 } 2399 2400 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) { 2401 return mCompatModePackages.compatibilityInfoForPackageLocked(ai); 2402 } 2403 2404 void enforceNotIsolatedCaller(String caller) { 2405 if (UserHandle.isIsolated(Binder.getCallingUid())) { 2406 throw new SecurityException("Isolated process not allowed to call " + caller); 2407 } 2408 } 2409 2410 public int getFrontActivityScreenCompatMode() { 2411 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode"); 2412 synchronized (this) { 2413 return mCompatModePackages.getFrontActivityScreenCompatModeLocked(); 2414 } 2415 } 2416 2417 public void setFrontActivityScreenCompatMode(int mode) { 2418 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 2419 "setFrontActivityScreenCompatMode"); 2420 synchronized (this) { 2421 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode); 2422 } 2423 } 2424 2425 public int getPackageScreenCompatMode(String packageName) { 2426 enforceNotIsolatedCaller("getPackageScreenCompatMode"); 2427 synchronized (this) { 2428 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName); 2429 } 2430 } 2431 2432 public void setPackageScreenCompatMode(String packageName, int mode) { 2433 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 2434 "setPackageScreenCompatMode"); 2435 synchronized (this) { 2436 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode); 2437 } 2438 } 2439 2440 public boolean getPackageAskScreenCompat(String packageName) { 2441 enforceNotIsolatedCaller("getPackageAskScreenCompat"); 2442 synchronized (this) { 2443 return mCompatModePackages.getPackageAskCompatModeLocked(packageName); 2444 } 2445 } 2446 2447 public void setPackageAskScreenCompat(String packageName, boolean ask) { 2448 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 2449 "setPackageAskScreenCompat"); 2450 synchronized (this) { 2451 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask); 2452 } 2453 } 2454 2455 void reportResumedActivityLocked(ActivityRecord r) { 2456 //Slog.i(TAG, "**** REPORT RESUME: " + r); 2457 updateUsageStats(r, true); 2458 } 2459 2460 private void dispatchProcessesChanged() { 2461 int N; 2462 synchronized (this) { 2463 N = mPendingProcessChanges.size(); 2464 if (mActiveProcessChanges.length < N) { 2465 mActiveProcessChanges = new ProcessChangeItem[N]; 2466 } 2467 mPendingProcessChanges.toArray(mActiveProcessChanges); 2468 mAvailProcessChanges.addAll(mPendingProcessChanges); 2469 mPendingProcessChanges.clear(); 2470 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "*** Delivering " + N + " process changes"); 2471 } 2472 int i = mProcessObservers.beginBroadcast(); 2473 while (i > 0) { 2474 i--; 2475 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 2476 if (observer != null) { 2477 try { 2478 for (int j=0; j<N; j++) { 2479 ProcessChangeItem item = mActiveProcessChanges[j]; 2480 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) { 2481 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "ACTIVITIES CHANGED pid=" 2482 + item.pid + " uid=" + item.uid + ": " 2483 + item.foregroundActivities); 2484 observer.onForegroundActivitiesChanged(item.pid, item.uid, 2485 item.foregroundActivities); 2486 } 2487 if ((item.changes&ProcessChangeItem.CHANGE_IMPORTANCE) != 0) { 2488 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG, "IMPORTANCE CHANGED pid=" 2489 + item.pid + " uid=" + item.uid + ": " + item.importance); 2490 observer.onImportanceChanged(item.pid, item.uid, 2491 item.importance); 2492 } 2493 } 2494 } catch (RemoteException e) { 2495 } 2496 } 2497 } 2498 mProcessObservers.finishBroadcast(); 2499 } 2500 2501 private void dispatchProcessDied(int pid, int uid) { 2502 int i = mProcessObservers.beginBroadcast(); 2503 while (i > 0) { 2504 i--; 2505 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 2506 if (observer != null) { 2507 try { 2508 observer.onProcessDied(pid, uid); 2509 } catch (RemoteException e) { 2510 } 2511 } 2512 } 2513 mProcessObservers.finishBroadcast(); 2514 } 2515 2516 final void doPendingActivityLaunchesLocked(boolean doResume) { 2517 final int N = mPendingActivityLaunches.size(); 2518 if (N <= 0) { 2519 return; 2520 } 2521 for (int i=0; i<N; i++) { 2522 PendingActivityLaunch pal = mPendingActivityLaunches.get(i); 2523 mMainStack.startActivityUncheckedLocked(pal.r, pal.sourceRecord, 2524 pal.startFlags, doResume && i == (N-1), null); 2525 } 2526 mPendingActivityLaunches.clear(); 2527 } 2528 2529 public final int startActivity(IApplicationThread caller, String callingPackage, 2530 Intent intent, String resolvedType, IBinder resultTo, 2531 String resultWho, int requestCode, int startFlags, 2532 String profileFile, ParcelFileDescriptor profileFd, Bundle options) { 2533 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, 2534 resultWho, requestCode, 2535 startFlags, profileFile, profileFd, options, UserHandle.getCallingUserId()); 2536 } 2537 2538 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 2539 Intent intent, String resolvedType, IBinder resultTo, 2540 String resultWho, int requestCode, int startFlags, 2541 String profileFile, ParcelFileDescriptor profileFd, Bundle options, int userId) { 2542 enforceNotIsolatedCaller("startActivity"); 2543 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2544 false, true, "startActivity", null); 2545 return mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 2546 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd, 2547 null, null, options, userId); 2548 } 2549 2550 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 2551 Intent intent, String resolvedType, IBinder resultTo, 2552 String resultWho, int requestCode, int startFlags, String profileFile, 2553 ParcelFileDescriptor profileFd, Bundle options, int userId) { 2554 enforceNotIsolatedCaller("startActivityAndWait"); 2555 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2556 false, true, "startActivityAndWait", null); 2557 WaitResult res = new WaitResult(); 2558 mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 2559 resultTo, resultWho, requestCode, startFlags, profileFile, profileFd, 2560 res, null, options, UserHandle.getCallingUserId()); 2561 return res; 2562 } 2563 2564 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage, 2565 Intent intent, String resolvedType, IBinder resultTo, 2566 String resultWho, int requestCode, int startFlags, Configuration config, 2567 Bundle options, int userId) { 2568 enforceNotIsolatedCaller("startActivityWithConfig"); 2569 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2570 false, true, "startActivityWithConfig", null); 2571 int ret = mMainStack.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 2572 resultTo, resultWho, requestCode, startFlags, 2573 null, null, null, config, options, userId); 2574 return ret; 2575 } 2576 2577 public int startActivityIntentSender(IApplicationThread caller, 2578 IntentSender intent, Intent fillInIntent, String resolvedType, 2579 IBinder resultTo, String resultWho, int requestCode, 2580 int flagsMask, int flagsValues, Bundle options) { 2581 enforceNotIsolatedCaller("startActivityIntentSender"); 2582 // Refuse possible leaked file descriptors 2583 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) { 2584 throw new IllegalArgumentException("File descriptors passed in Intent"); 2585 } 2586 2587 IIntentSender sender = intent.getTarget(); 2588 if (!(sender instanceof PendingIntentRecord)) { 2589 throw new IllegalArgumentException("Bad PendingIntent object"); 2590 } 2591 2592 PendingIntentRecord pir = (PendingIntentRecord)sender; 2593 2594 synchronized (this) { 2595 // If this is coming from the currently resumed activity, it is 2596 // effectively saying that app switches are allowed at this point. 2597 if (mMainStack.mResumedActivity != null 2598 && mMainStack.mResumedActivity.info.applicationInfo.uid == 2599 Binder.getCallingUid()) { 2600 mAppSwitchesAllowedTime = 0; 2601 } 2602 } 2603 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null, 2604 resultTo, resultWho, requestCode, flagsMask, flagsValues, options); 2605 return ret; 2606 } 2607 2608 public boolean startNextMatchingActivity(IBinder callingActivity, 2609 Intent intent, Bundle options) { 2610 // Refuse possible leaked file descriptors 2611 if (intent != null && intent.hasFileDescriptors() == true) { 2612 throw new IllegalArgumentException("File descriptors passed in Intent"); 2613 } 2614 2615 synchronized (this) { 2616 ActivityRecord r = mMainStack.isInStackLocked(callingActivity); 2617 if (r == null) { 2618 ActivityOptions.abort(options); 2619 return false; 2620 } 2621 if (r.app == null || r.app.thread == null) { 2622 // The caller is not running... d'oh! 2623 ActivityOptions.abort(options); 2624 return false; 2625 } 2626 intent = new Intent(intent); 2627 // The caller is not allowed to change the data. 2628 intent.setDataAndType(r.intent.getData(), r.intent.getType()); 2629 // And we are resetting to find the next component... 2630 intent.setComponent(null); 2631 2632 ActivityInfo aInfo = null; 2633 try { 2634 List<ResolveInfo> resolves = 2635 AppGlobals.getPackageManager().queryIntentActivities( 2636 intent, r.resolvedType, 2637 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS, 2638 UserHandle.getCallingUserId()); 2639 2640 // Look for the original activity in the list... 2641 final int N = resolves != null ? resolves.size() : 0; 2642 for (int i=0; i<N; i++) { 2643 ResolveInfo rInfo = resolves.get(i); 2644 if (rInfo.activityInfo.packageName.equals(r.packageName) 2645 && rInfo.activityInfo.name.equals(r.info.name)) { 2646 // We found the current one... the next matching is 2647 // after it. 2648 i++; 2649 if (i<N) { 2650 aInfo = resolves.get(i).activityInfo; 2651 } 2652 break; 2653 } 2654 } 2655 } catch (RemoteException e) { 2656 } 2657 2658 if (aInfo == null) { 2659 // Nobody who is next! 2660 ActivityOptions.abort(options); 2661 return false; 2662 } 2663 2664 intent.setComponent(new ComponentName( 2665 aInfo.applicationInfo.packageName, aInfo.name)); 2666 intent.setFlags(intent.getFlags()&~( 2667 Intent.FLAG_ACTIVITY_FORWARD_RESULT| 2668 Intent.FLAG_ACTIVITY_CLEAR_TOP| 2669 Intent.FLAG_ACTIVITY_MULTIPLE_TASK| 2670 Intent.FLAG_ACTIVITY_NEW_TASK)); 2671 2672 // Okay now we need to start the new activity, replacing the 2673 // currently running activity. This is a little tricky because 2674 // we want to start the new one as if the current one is finished, 2675 // but not finish the current one first so that there is no flicker. 2676 // And thus... 2677 final boolean wasFinishing = r.finishing; 2678 r.finishing = true; 2679 2680 // Propagate reply information over to the new activity. 2681 final ActivityRecord resultTo = r.resultTo; 2682 final String resultWho = r.resultWho; 2683 final int requestCode = r.requestCode; 2684 r.resultTo = null; 2685 if (resultTo != null) { 2686 resultTo.removeResultsLocked(r, resultWho, requestCode); 2687 } 2688 2689 final long origId = Binder.clearCallingIdentity(); 2690 int res = mMainStack.startActivityLocked(r.app.thread, intent, 2691 r.resolvedType, aInfo, resultTo != null ? resultTo.appToken : null, 2692 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 0, 2693 options, false, null); 2694 Binder.restoreCallingIdentity(origId); 2695 2696 r.finishing = wasFinishing; 2697 if (res != ActivityManager.START_SUCCESS) { 2698 return false; 2699 } 2700 return true; 2701 } 2702 } 2703 2704 final int startActivityInPackage(int uid, String callingPackage, 2705 Intent intent, String resolvedType, IBinder resultTo, 2706 String resultWho, int requestCode, int startFlags, Bundle options, int userId) { 2707 2708 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2709 false, true, "startActivityInPackage", null); 2710 2711 int ret = mMainStack.startActivityMayWait(null, uid, callingPackage, intent, resolvedType, 2712 resultTo, resultWho, requestCode, startFlags, 2713 null, null, null, null, options, userId); 2714 return ret; 2715 } 2716 2717 public final int startActivities(IApplicationThread caller, String callingPackage, 2718 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options, 2719 int userId) { 2720 enforceNotIsolatedCaller("startActivities"); 2721 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2722 false, true, "startActivity", null); 2723 int ret = mMainStack.startActivities(caller, -1, callingPackage, intents, 2724 resolvedTypes, resultTo, options, userId); 2725 return ret; 2726 } 2727 2728 final int startActivitiesInPackage(int uid, String callingPackage, 2729 Intent[] intents, String[] resolvedTypes, IBinder resultTo, 2730 Bundle options, int userId) { 2731 2732 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 2733 false, true, "startActivityInPackage", null); 2734 int ret = mMainStack.startActivities(null, uid, callingPackage, intents, resolvedTypes, 2735 resultTo, options, userId); 2736 return ret; 2737 } 2738 2739 final void addRecentTaskLocked(TaskRecord task) { 2740 int N = mRecentTasks.size(); 2741 // Quick case: check if the top-most recent task is the same. 2742 if (N > 0 && mRecentTasks.get(0) == task) { 2743 return; 2744 } 2745 // Remove any existing entries that are the same kind of task. 2746 for (int i=0; i<N; i++) { 2747 TaskRecord tr = mRecentTasks.get(i); 2748 if (task.userId == tr.userId 2749 && ((task.affinity != null && task.affinity.equals(tr.affinity)) 2750 || (task.intent != null && task.intent.filterEquals(tr.intent)))) { 2751 mRecentTasks.remove(i); 2752 i--; 2753 N--; 2754 if (task.intent == null) { 2755 // If the new recent task we are adding is not fully 2756 // specified, then replace it with the existing recent task. 2757 task = tr; 2758 } 2759 } 2760 } 2761 if (N >= MAX_RECENT_TASKS) { 2762 mRecentTasks.remove(N-1); 2763 } 2764 mRecentTasks.add(0, task); 2765 } 2766 2767 public void setRequestedOrientation(IBinder token, 2768 int requestedOrientation) { 2769 synchronized (this) { 2770 ActivityRecord r = mMainStack.isInStackLocked(token); 2771 if (r == null) { 2772 return; 2773 } 2774 final long origId = Binder.clearCallingIdentity(); 2775 mWindowManager.setAppOrientation(r.appToken, requestedOrientation); 2776 Configuration config = mWindowManager.updateOrientationFromAppTokens( 2777 mConfiguration, 2778 r.mayFreezeScreenLocked(r.app) ? r.appToken : null); 2779 if (config != null) { 2780 r.frozenBeforeDestroy = true; 2781 if (!updateConfigurationLocked(config, r, false, false)) { 2782 mMainStack.resumeTopActivityLocked(null); 2783 } 2784 } 2785 Binder.restoreCallingIdentity(origId); 2786 } 2787 } 2788 2789 public int getRequestedOrientation(IBinder token) { 2790 synchronized (this) { 2791 ActivityRecord r = mMainStack.isInStackLocked(token); 2792 if (r == null) { 2793 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 2794 } 2795 return mWindowManager.getAppOrientation(r.appToken); 2796 } 2797 } 2798 2799 /** 2800 * This is the internal entry point for handling Activity.finish(). 2801 * 2802 * @param token The Binder token referencing the Activity we want to finish. 2803 * @param resultCode Result code, if any, from this Activity. 2804 * @param resultData Result data (Intent), if any, from this Activity. 2805 * 2806 * @return Returns true if the activity successfully finished, or false if it is still running. 2807 */ 2808 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData) { 2809 // Refuse possible leaked file descriptors 2810 if (resultData != null && resultData.hasFileDescriptors() == true) { 2811 throw new IllegalArgumentException("File descriptors passed in Intent"); 2812 } 2813 2814 synchronized(this) { 2815 if (mController != null) { 2816 // Find the first activity that is not finishing. 2817 ActivityRecord next = mMainStack.topRunningActivityLocked(token, 0); 2818 if (next != null) { 2819 // ask watcher if this is allowed 2820 boolean resumeOK = true; 2821 try { 2822 resumeOK = mController.activityResuming(next.packageName); 2823 } catch (RemoteException e) { 2824 mController = null; 2825 Watchdog.getInstance().setActivityController(null); 2826 } 2827 2828 if (!resumeOK) { 2829 return false; 2830 } 2831 } 2832 } 2833 final long origId = Binder.clearCallingIdentity(); 2834 boolean res = mMainStack.requestFinishActivityLocked(token, resultCode, 2835 resultData, "app-request", true); 2836 Binder.restoreCallingIdentity(origId); 2837 return res; 2838 } 2839 } 2840 2841 public final void finishHeavyWeightApp() { 2842 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 2843 != PackageManager.PERMISSION_GRANTED) { 2844 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 2845 + Binder.getCallingPid() 2846 + ", uid=" + Binder.getCallingUid() 2847 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 2848 Slog.w(TAG, msg); 2849 throw new SecurityException(msg); 2850 } 2851 2852 synchronized(this) { 2853 if (mHeavyWeightProcess == null) { 2854 return; 2855 } 2856 2857 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>( 2858 mHeavyWeightProcess.activities); 2859 for (int i=0; i<activities.size(); i++) { 2860 ActivityRecord r = activities.get(i); 2861 if (!r.finishing) { 2862 int index = mMainStack.indexOfTokenLocked(r.appToken); 2863 if (index >= 0) { 2864 mMainStack.finishActivityLocked(r, index, Activity.RESULT_CANCELED, 2865 null, "finish-heavy", true); 2866 } 2867 } 2868 } 2869 2870 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 2871 mHeavyWeightProcess.userId, 0)); 2872 mHeavyWeightProcess = null; 2873 } 2874 } 2875 2876 public void crashApplication(int uid, int initialPid, String packageName, 2877 String message) { 2878 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 2879 != PackageManager.PERMISSION_GRANTED) { 2880 String msg = "Permission Denial: crashApplication() from pid=" 2881 + Binder.getCallingPid() 2882 + ", uid=" + Binder.getCallingUid() 2883 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 2884 Slog.w(TAG, msg); 2885 throw new SecurityException(msg); 2886 } 2887 2888 synchronized(this) { 2889 ProcessRecord proc = null; 2890 2891 // Figure out which process to kill. We don't trust that initialPid 2892 // still has any relation to current pids, so must scan through the 2893 // list. 2894 synchronized (mPidsSelfLocked) { 2895 for (int i=0; i<mPidsSelfLocked.size(); i++) { 2896 ProcessRecord p = mPidsSelfLocked.valueAt(i); 2897 if (p.uid != uid) { 2898 continue; 2899 } 2900 if (p.pid == initialPid) { 2901 proc = p; 2902 break; 2903 } 2904 for (String str : p.pkgList) { 2905 if (str.equals(packageName)) { 2906 proc = p; 2907 } 2908 } 2909 } 2910 } 2911 2912 if (proc == null) { 2913 Slog.w(TAG, "crashApplication: nothing for uid=" + uid 2914 + " initialPid=" + initialPid 2915 + " packageName=" + packageName); 2916 return; 2917 } 2918 2919 if (proc.thread != null) { 2920 if (proc.pid == Process.myPid()) { 2921 Log.w(TAG, "crashApplication: trying to crash self!"); 2922 return; 2923 } 2924 long ident = Binder.clearCallingIdentity(); 2925 try { 2926 proc.thread.scheduleCrash(message); 2927 } catch (RemoteException e) { 2928 } 2929 Binder.restoreCallingIdentity(ident); 2930 } 2931 } 2932 } 2933 2934 public final void finishSubActivity(IBinder token, String resultWho, 2935 int requestCode) { 2936 synchronized(this) { 2937 final long origId = Binder.clearCallingIdentity(); 2938 mMainStack.finishSubActivityLocked(token, resultWho, requestCode); 2939 Binder.restoreCallingIdentity(origId); 2940 } 2941 } 2942 2943 public boolean finishActivityAffinity(IBinder token) { 2944 synchronized(this) { 2945 final long origId = Binder.clearCallingIdentity(); 2946 boolean res = mMainStack.finishActivityAffinityLocked(token); 2947 Binder.restoreCallingIdentity(origId); 2948 return res; 2949 } 2950 } 2951 2952 public boolean willActivityBeVisible(IBinder token) { 2953 synchronized(this) { 2954 int i; 2955 for (i=mMainStack.mHistory.size()-1; i>=0; i--) { 2956 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 2957 if (r.appToken == token) { 2958 return true; 2959 } 2960 if (r.fullscreen && !r.finishing) { 2961 return false; 2962 } 2963 } 2964 return true; 2965 } 2966 } 2967 2968 public void overridePendingTransition(IBinder token, String packageName, 2969 int enterAnim, int exitAnim) { 2970 synchronized(this) { 2971 ActivityRecord self = mMainStack.isInStackLocked(token); 2972 if (self == null) { 2973 return; 2974 } 2975 2976 final long origId = Binder.clearCallingIdentity(); 2977 2978 if (self.state == ActivityState.RESUMED 2979 || self.state == ActivityState.PAUSING) { 2980 mWindowManager.overridePendingAppTransition(packageName, 2981 enterAnim, exitAnim, null); 2982 } 2983 2984 Binder.restoreCallingIdentity(origId); 2985 } 2986 } 2987 2988 /** 2989 * Main function for removing an existing process from the activity manager 2990 * as a result of that process going away. Clears out all connections 2991 * to the process. 2992 */ 2993 private final void handleAppDiedLocked(ProcessRecord app, 2994 boolean restarting, boolean allowRestart) { 2995 cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1); 2996 if (!restarting) { 2997 mLruProcesses.remove(app); 2998 } 2999 3000 if (mProfileProc == app) { 3001 clearProfilerLocked(); 3002 } 3003 3004 // Just in case... 3005 if (mMainStack.mPausingActivity != null && mMainStack.mPausingActivity.app == app) { 3006 if (DEBUG_PAUSE || DEBUG_CLEANUP) Slog.v(TAG, 3007 "App died while pausing: " + mMainStack.mPausingActivity); 3008 mMainStack.mPausingActivity = null; 3009 } 3010 if (mMainStack.mLastPausedActivity != null && mMainStack.mLastPausedActivity.app == app) { 3011 mMainStack.mLastPausedActivity = null; 3012 } 3013 3014 // Remove this application's activities from active lists. 3015 boolean hasVisibleActivities = mMainStack.removeHistoryRecordsForAppLocked(app); 3016 3017 app.activities.clear(); 3018 3019 if (app.instrumentationClass != null) { 3020 Slog.w(TAG, "Crash of app " + app.processName 3021 + " running instrumentation " + app.instrumentationClass); 3022 Bundle info = new Bundle(); 3023 info.putString("shortMsg", "Process crashed."); 3024 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 3025 } 3026 3027 if (!restarting) { 3028 if (!mMainStack.resumeTopActivityLocked(null)) { 3029 // If there was nothing to resume, and we are not already 3030 // restarting this process, but there is a visible activity that 3031 // is hosted by the process... then make sure all visible 3032 // activities are running, taking care of restarting this 3033 // process. 3034 if (hasVisibleActivities) { 3035 mMainStack.ensureActivitiesVisibleLocked(null, 0); 3036 } 3037 } 3038 } 3039 } 3040 3041 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) { 3042 IBinder threadBinder = thread.asBinder(); 3043 // Find the application record. 3044 for (int i=mLruProcesses.size()-1; i>=0; i--) { 3045 ProcessRecord rec = mLruProcesses.get(i); 3046 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 3047 return i; 3048 } 3049 } 3050 return -1; 3051 } 3052 3053 final ProcessRecord getRecordForAppLocked( 3054 IApplicationThread thread) { 3055 if (thread == null) { 3056 return null; 3057 } 3058 3059 int appIndex = getLRURecordIndexForAppLocked(thread); 3060 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null; 3061 } 3062 3063 final void appDiedLocked(ProcessRecord app, int pid, 3064 IApplicationThread thread) { 3065 3066 mProcDeaths[0]++; 3067 3068 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 3069 synchronized (stats) { 3070 stats.noteProcessDiedLocked(app.info.uid, pid); 3071 } 3072 3073 // Clean up already done if the process has been re-started. 3074 if (app.pid == pid && app.thread != null && 3075 app.thread.asBinder() == thread.asBinder()) { 3076 if (!app.killedBackground) { 3077 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 3078 + ") has died."); 3079 } 3080 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 3081 if (DEBUG_CLEANUP) Slog.v( 3082 TAG, "Dying app: " + app + ", pid: " + pid 3083 + ", thread: " + thread.asBinder()); 3084 boolean doLowMem = app.instrumentationClass == null; 3085 handleAppDiedLocked(app, false, true); 3086 3087 if (doLowMem) { 3088 // If there are no longer any background processes running, 3089 // and the app that died was not running instrumentation, 3090 // then tell everyone we are now low on memory. 3091 boolean haveBg = false; 3092 for (int i=mLruProcesses.size()-1; i>=0; i--) { 3093 ProcessRecord rec = mLruProcesses.get(i); 3094 if (rec.thread != null && rec.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 3095 haveBg = true; 3096 break; 3097 } 3098 } 3099 3100 if (!haveBg) { 3101 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size()); 3102 long now = SystemClock.uptimeMillis(); 3103 for (int i=mLruProcesses.size()-1; i>=0; i--) { 3104 ProcessRecord rec = mLruProcesses.get(i); 3105 if (rec != app && rec.thread != null && 3106 (rec.lastLowMemory+GC_MIN_INTERVAL) <= now) { 3107 // The low memory report is overriding any current 3108 // state for a GC request. Make sure to do 3109 // heavy/important/visible/foreground processes first. 3110 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 3111 rec.lastRequestedGc = 0; 3112 } else { 3113 rec.lastRequestedGc = rec.lastLowMemory; 3114 } 3115 rec.reportLowMemory = true; 3116 rec.lastLowMemory = now; 3117 mProcessesToGc.remove(rec); 3118 addProcessToGcListLocked(rec); 3119 } 3120 } 3121 mHandler.sendEmptyMessage(REPORT_MEM_USAGE); 3122 scheduleAppGcsLocked(); 3123 } 3124 } 3125 } else if (app.pid != pid) { 3126 // A new process has already been started. 3127 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 3128 + ") has died and restarted (pid " + app.pid + ")."); 3129 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 3130 } else if (DEBUG_PROCESSES) { 3131 Slog.d(TAG, "Received spurious death notification for thread " 3132 + thread.asBinder()); 3133 } 3134 } 3135 3136 /** 3137 * If a stack trace dump file is configured, dump process stack traces. 3138 * @param clearTraces causes the dump file to be erased prior to the new 3139 * traces being written, if true; when false, the new traces will be 3140 * appended to any existing file content. 3141 * @param firstPids of dalvik VM processes to dump stack traces for first 3142 * @param lastPids of dalvik VM processes to dump stack traces for last 3143 * @param nativeProcs optional list of native process names to dump stack crawls 3144 * @return file containing stack traces, or null if no dump file is configured 3145 */ 3146 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, 3147 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) { 3148 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 3149 if (tracesPath == null || tracesPath.length() == 0) { 3150 return null; 3151 } 3152 3153 File tracesFile = new File(tracesPath); 3154 try { 3155 File tracesDir = tracesFile.getParentFile(); 3156 if (!tracesDir.exists()) { 3157 tracesFile.mkdirs(); 3158 if (!SELinux.restorecon(tracesDir)) { 3159 return null; 3160 } 3161 } 3162 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 3163 3164 if (clearTraces && tracesFile.exists()) tracesFile.delete(); 3165 tracesFile.createNewFile(); 3166 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 3167 } catch (IOException e) { 3168 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e); 3169 return null; 3170 } 3171 3172 dumpStackTraces(tracesPath, firstPids, processStats, lastPids, nativeProcs); 3173 return tracesFile; 3174 } 3175 3176 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids, 3177 ProcessStats processStats, SparseArray<Boolean> lastPids, String[] nativeProcs) { 3178 // Use a FileObserver to detect when traces finish writing. 3179 // The order of traces is considered important to maintain for legibility. 3180 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) { 3181 public synchronized void onEvent(int event, String path) { notify(); } 3182 }; 3183 3184 try { 3185 observer.startWatching(); 3186 3187 // First collect all of the stacks of the most important pids. 3188 if (firstPids != null) { 3189 try { 3190 int num = firstPids.size(); 3191 for (int i = 0; i < num; i++) { 3192 synchronized (observer) { 3193 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT); 3194 observer.wait(200); // Wait for write-close, give up after 200msec 3195 } 3196 } 3197 } catch (InterruptedException e) { 3198 Log.wtf(TAG, e); 3199 } 3200 } 3201 3202 // Next measure CPU usage. 3203 if (processStats != null) { 3204 processStats.init(); 3205 System.gc(); 3206 processStats.update(); 3207 try { 3208 synchronized (processStats) { 3209 processStats.wait(500); // measure over 1/2 second. 3210 } 3211 } catch (InterruptedException e) { 3212 } 3213 processStats.update(); 3214 3215 // We'll take the stack crawls of just the top apps using CPU. 3216 final int N = processStats.countWorkingStats(); 3217 int numProcs = 0; 3218 for (int i=0; i<N && numProcs<5; i++) { 3219 ProcessStats.Stats stats = processStats.getWorkingStats(i); 3220 if (lastPids.indexOfKey(stats.pid) >= 0) { 3221 numProcs++; 3222 try { 3223 synchronized (observer) { 3224 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT); 3225 observer.wait(200); // Wait for write-close, give up after 200msec 3226 } 3227 } catch (InterruptedException e) { 3228 Log.wtf(TAG, e); 3229 } 3230 3231 } 3232 } 3233 } 3234 3235 } finally { 3236 observer.stopWatching(); 3237 } 3238 3239 if (nativeProcs != null) { 3240 int[] pids = Process.getPidsForCommands(nativeProcs); 3241 if (pids != null) { 3242 for (int pid : pids) { 3243 Debug.dumpNativeBacktraceToFile(pid, tracesPath); 3244 } 3245 } 3246 } 3247 } 3248 3249 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) { 3250 if (true || IS_USER_BUILD) { 3251 return; 3252 } 3253 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 3254 if (tracesPath == null || tracesPath.length() == 0) { 3255 return; 3256 } 3257 3258 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 3259 StrictMode.allowThreadDiskWrites(); 3260 try { 3261 final File tracesFile = new File(tracesPath); 3262 final File tracesDir = tracesFile.getParentFile(); 3263 final File tracesTmp = new File(tracesDir, "__tmp__"); 3264 try { 3265 if (!tracesDir.exists()) { 3266 tracesFile.mkdirs(); 3267 if (!SELinux.restorecon(tracesDir.getPath())) { 3268 return; 3269 } 3270 } 3271 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 3272 3273 if (tracesFile.exists()) { 3274 tracesTmp.delete(); 3275 tracesFile.renameTo(tracesTmp); 3276 } 3277 StringBuilder sb = new StringBuilder(); 3278 Time tobj = new Time(); 3279 tobj.set(System.currentTimeMillis()); 3280 sb.append(tobj.format("%Y-%m-%d %H:%M:%S")); 3281 sb.append(": "); 3282 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb); 3283 sb.append(" since "); 3284 sb.append(msg); 3285 FileOutputStream fos = new FileOutputStream(tracesFile); 3286 fos.write(sb.toString().getBytes()); 3287 if (app == null) { 3288 fos.write("\n*** No application process!".getBytes()); 3289 } 3290 fos.close(); 3291 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 3292 } catch (IOException e) { 3293 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e); 3294 return; 3295 } 3296 3297 if (app != null) { 3298 ArrayList<Integer> firstPids = new ArrayList<Integer>(); 3299 firstPids.add(app.pid); 3300 dumpStackTraces(tracesPath, firstPids, null, null, null); 3301 } 3302 3303 File lastTracesFile = null; 3304 File curTracesFile = null; 3305 for (int i=9; i>=0; i--) { 3306 String name = String.format("slow%02d.txt", i); 3307 curTracesFile = new File(tracesDir, name); 3308 if (curTracesFile.exists()) { 3309 if (lastTracesFile != null) { 3310 curTracesFile.renameTo(lastTracesFile); 3311 } else { 3312 curTracesFile.delete(); 3313 } 3314 } 3315 lastTracesFile = curTracesFile; 3316 } 3317 tracesFile.renameTo(curTracesFile); 3318 if (tracesTmp.exists()) { 3319 tracesTmp.renameTo(tracesFile); 3320 } 3321 } finally { 3322 StrictMode.setThreadPolicy(oldPolicy); 3323 } 3324 } 3325 3326 final void appNotResponding(ProcessRecord app, ActivityRecord activity, 3327 ActivityRecord parent, boolean aboveSystem, final String annotation) { 3328 ArrayList<Integer> firstPids = new ArrayList<Integer>(5); 3329 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20); 3330 3331 if (mController != null) { 3332 try { 3333 // 0 == continue, -1 = kill process immediately 3334 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation); 3335 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid); 3336 } catch (RemoteException e) { 3337 mController = null; 3338 Watchdog.getInstance().setActivityController(null); 3339 } 3340 } 3341 3342 long anrTime = SystemClock.uptimeMillis(); 3343 if (MONITOR_CPU_USAGE) { 3344 updateCpuStatsNow(); 3345 } 3346 3347 synchronized (this) { 3348 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down. 3349 if (mShuttingDown) { 3350 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation); 3351 return; 3352 } else if (app.notResponding) { 3353 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation); 3354 return; 3355 } else if (app.crashing) { 3356 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation); 3357 return; 3358 } 3359 3360 // In case we come through here for the same app before completing 3361 // this one, mark as anring now so we will bail out. 3362 app.notResponding = true; 3363 3364 // Log the ANR to the event log. 3365 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid, 3366 app.processName, app.info.flags, annotation); 3367 3368 // Dump thread traces as quickly as we can, starting with "interesting" processes. 3369 firstPids.add(app.pid); 3370 3371 int parentPid = app.pid; 3372 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid; 3373 if (parentPid != app.pid) firstPids.add(parentPid); 3374 3375 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID); 3376 3377 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 3378 ProcessRecord r = mLruProcesses.get(i); 3379 if (r != null && r.thread != null) { 3380 int pid = r.pid; 3381 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) { 3382 if (r.persistent) { 3383 firstPids.add(pid); 3384 } else { 3385 lastPids.put(pid, Boolean.TRUE); 3386 } 3387 } 3388 } 3389 } 3390 } 3391 3392 // Log the ANR to the main log. 3393 StringBuilder info = new StringBuilder(); 3394 info.setLength(0); 3395 info.append("ANR in ").append(app.processName); 3396 if (activity != null && activity.shortComponentName != null) { 3397 info.append(" (").append(activity.shortComponentName).append(")"); 3398 } 3399 info.append("\n"); 3400 if (annotation != null) { 3401 info.append("Reason: ").append(annotation).append("\n"); 3402 } 3403 if (parent != null && parent != activity) { 3404 info.append("Parent: ").append(parent.shortComponentName).append("\n"); 3405 } 3406 3407 final ProcessStats processStats = new ProcessStats(true); 3408 3409 File tracesFile = dumpStackTraces(true, firstPids, processStats, lastPids, null); 3410 3411 String cpuInfo = null; 3412 if (MONITOR_CPU_USAGE) { 3413 updateCpuStatsNow(); 3414 synchronized (mProcessStatsThread) { 3415 cpuInfo = mProcessStats.printCurrentState(anrTime); 3416 } 3417 info.append(processStats.printCurrentLoad()); 3418 info.append(cpuInfo); 3419 } 3420 3421 info.append(processStats.printCurrentState(anrTime)); 3422 3423 Slog.e(TAG, info.toString()); 3424 if (tracesFile == null) { 3425 // There is no trace file, so dump (only) the alleged culprit's threads to the log 3426 Process.sendSignal(app.pid, Process.SIGNAL_QUIT); 3427 } 3428 3429 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation, 3430 cpuInfo, tracesFile, null); 3431 3432 if (mController != null) { 3433 try { 3434 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately 3435 int res = mController.appNotResponding(app.processName, app.pid, info.toString()); 3436 if (res != 0) { 3437 if (res < 0 && app.pid != MY_PID) Process.killProcess(app.pid); 3438 return; 3439 } 3440 } catch (RemoteException e) { 3441 mController = null; 3442 Watchdog.getInstance().setActivityController(null); 3443 } 3444 } 3445 3446 // Unless configured otherwise, swallow ANRs in background processes & kill the process. 3447 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 3448 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 3449 3450 synchronized (this) { 3451 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) { 3452 Slog.w(TAG, "Killing " + app + ": background ANR"); 3453 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, app.pid, 3454 app.processName, app.setAdj, "background ANR"); 3455 Process.killProcessQuiet(app.pid); 3456 return; 3457 } 3458 3459 // Set the app's notResponding state, and look up the errorReportReceiver 3460 makeAppNotRespondingLocked(app, 3461 activity != null ? activity.shortComponentName : null, 3462 annotation != null ? "ANR " + annotation : "ANR", 3463 info.toString()); 3464 3465 // Bring up the infamous App Not Responding dialog 3466 Message msg = Message.obtain(); 3467 HashMap map = new HashMap(); 3468 msg.what = SHOW_NOT_RESPONDING_MSG; 3469 msg.obj = map; 3470 msg.arg1 = aboveSystem ? 1 : 0; 3471 map.put("app", app); 3472 if (activity != null) { 3473 map.put("activity", activity); 3474 } 3475 3476 mHandler.sendMessage(msg); 3477 } 3478 } 3479 3480 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) { 3481 if (!mLaunchWarningShown) { 3482 mLaunchWarningShown = true; 3483 mHandler.post(new Runnable() { 3484 @Override 3485 public void run() { 3486 synchronized (ActivityManagerService.this) { 3487 final Dialog d = new LaunchWarningWindow(mContext, cur, next); 3488 d.show(); 3489 mHandler.postDelayed(new Runnable() { 3490 @Override 3491 public void run() { 3492 synchronized (ActivityManagerService.this) { 3493 d.dismiss(); 3494 mLaunchWarningShown = false; 3495 } 3496 } 3497 }, 4000); 3498 } 3499 } 3500 }); 3501 } 3502 } 3503 3504 public boolean clearApplicationUserData(final String packageName, 3505 final IPackageDataObserver observer, int userId) { 3506 enforceNotIsolatedCaller("clearApplicationUserData"); 3507 int uid = Binder.getCallingUid(); 3508 int pid = Binder.getCallingPid(); 3509 userId = handleIncomingUser(pid, uid, 3510 userId, false, true, "clearApplicationUserData", null); 3511 long callingId = Binder.clearCallingIdentity(); 3512 try { 3513 IPackageManager pm = AppGlobals.getPackageManager(); 3514 int pkgUid = -1; 3515 synchronized(this) { 3516 try { 3517 pkgUid = pm.getPackageUid(packageName, userId); 3518 } catch (RemoteException e) { 3519 } 3520 if (pkgUid == -1) { 3521 Slog.w(TAG, "Invalid packageName: " + packageName); 3522 if (observer != null) { 3523 try { 3524 observer.onRemoveCompleted(packageName, false); 3525 } catch (RemoteException e) { 3526 Slog.i(TAG, "Observer no longer exists."); 3527 } 3528 } 3529 return false; 3530 } 3531 if (uid == pkgUid || checkComponentPermission( 3532 android.Manifest.permission.CLEAR_APP_USER_DATA, 3533 pid, uid, -1, true) 3534 == PackageManager.PERMISSION_GRANTED) { 3535 forceStopPackageLocked(packageName, pkgUid); 3536 } else { 3537 throw new SecurityException(pid+" does not have permission:"+ 3538 android.Manifest.permission.CLEAR_APP_USER_DATA+" to clear data" + 3539 "for process:"+packageName); 3540 } 3541 } 3542 3543 try { 3544 //clear application user data 3545 pm.clearApplicationUserData(packageName, observer, userId); 3546 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 3547 Uri.fromParts("package", packageName, null)); 3548 intent.putExtra(Intent.EXTRA_UID, pkgUid); 3549 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent, 3550 null, null, 0, null, null, null, false, false, userId); 3551 } catch (RemoteException e) { 3552 } 3553 } finally { 3554 Binder.restoreCallingIdentity(callingId); 3555 } 3556 return true; 3557 } 3558 3559 public void killBackgroundProcesses(final String packageName, int userId) { 3560 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3561 != PackageManager.PERMISSION_GRANTED && 3562 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 3563 != PackageManager.PERMISSION_GRANTED) { 3564 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 3565 + Binder.getCallingPid() 3566 + ", uid=" + Binder.getCallingUid() 3567 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3568 Slog.w(TAG, msg); 3569 throw new SecurityException(msg); 3570 } 3571 3572 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 3573 userId, true, true, "killBackgroundProcesses", null); 3574 long callingId = Binder.clearCallingIdentity(); 3575 try { 3576 IPackageManager pm = AppGlobals.getPackageManager(); 3577 synchronized(this) { 3578 int appId = -1; 3579 try { 3580 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0)); 3581 } catch (RemoteException e) { 3582 } 3583 if (appId == -1) { 3584 Slog.w(TAG, "Invalid packageName: " + packageName); 3585 return; 3586 } 3587 killPackageProcessesLocked(packageName, appId, userId, 3588 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background"); 3589 } 3590 } finally { 3591 Binder.restoreCallingIdentity(callingId); 3592 } 3593 } 3594 3595 public void killAllBackgroundProcesses() { 3596 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 3597 != PackageManager.PERMISSION_GRANTED) { 3598 String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 3599 + Binder.getCallingPid() 3600 + ", uid=" + Binder.getCallingUid() 3601 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 3602 Slog.w(TAG, msg); 3603 throw new SecurityException(msg); 3604 } 3605 3606 long callingId = Binder.clearCallingIdentity(); 3607 try { 3608 synchronized(this) { 3609 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 3610 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) { 3611 final int NA = apps.size(); 3612 for (int ia=0; ia<NA; ia++) { 3613 ProcessRecord app = apps.valueAt(ia); 3614 if (app.persistent) { 3615 // we don't kill persistent processes 3616 continue; 3617 } 3618 if (app.removed) { 3619 procs.add(app); 3620 } else if (app.setAdj >= ProcessList.HIDDEN_APP_MIN_ADJ) { 3621 app.removed = true; 3622 procs.add(app); 3623 } 3624 } 3625 } 3626 3627 int N = procs.size(); 3628 for (int i=0; i<N; i++) { 3629 removeProcessLocked(procs.get(i), false, true, "kill all background"); 3630 } 3631 } 3632 } finally { 3633 Binder.restoreCallingIdentity(callingId); 3634 } 3635 } 3636 3637 public void forceStopPackage(final String packageName, int userId) { 3638 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 3639 != PackageManager.PERMISSION_GRANTED) { 3640 String msg = "Permission Denial: forceStopPackage() from pid=" 3641 + Binder.getCallingPid() 3642 + ", uid=" + Binder.getCallingUid() 3643 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 3644 Slog.w(TAG, msg); 3645 throw new SecurityException(msg); 3646 } 3647 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 3648 userId, true, true, "forceStopPackage", null); 3649 long callingId = Binder.clearCallingIdentity(); 3650 try { 3651 IPackageManager pm = AppGlobals.getPackageManager(); 3652 synchronized(this) { 3653 int[] users = userId == UserHandle.USER_ALL 3654 ? getUsersLocked() : new int[] { userId }; 3655 for (int user : users) { 3656 int pkgUid = -1; 3657 try { 3658 pkgUid = pm.getPackageUid(packageName, user); 3659 } catch (RemoteException e) { 3660 } 3661 if (pkgUid == -1) { 3662 Slog.w(TAG, "Invalid packageName: " + packageName); 3663 continue; 3664 } 3665 try { 3666 pm.setPackageStoppedState(packageName, true, user); 3667 } catch (RemoteException e) { 3668 } catch (IllegalArgumentException e) { 3669 Slog.w(TAG, "Failed trying to unstop package " 3670 + packageName + ": " + e); 3671 } 3672 if (isUserRunningLocked(user, false)) { 3673 forceStopPackageLocked(packageName, pkgUid); 3674 } 3675 } 3676 } 3677 } finally { 3678 Binder.restoreCallingIdentity(callingId); 3679 } 3680 } 3681 3682 /* 3683 * The pkg name and app id have to be specified. 3684 */ 3685 public void killApplicationWithAppId(String pkg, int appid) { 3686 if (pkg == null) { 3687 return; 3688 } 3689 // Make sure the uid is valid. 3690 if (appid < 0) { 3691 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 3692 return; 3693 } 3694 int callerUid = Binder.getCallingUid(); 3695 // Only the system server can kill an application 3696 if (callerUid == Process.SYSTEM_UID) { 3697 // Post an aysnc message to kill the application 3698 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 3699 msg.arg1 = appid; 3700 msg.arg2 = 0; 3701 msg.obj = pkg; 3702 mHandler.sendMessage(msg); 3703 } else { 3704 throw new SecurityException(callerUid + " cannot kill pkg: " + 3705 pkg); 3706 } 3707 } 3708 3709 public void closeSystemDialogs(String reason) { 3710 enforceNotIsolatedCaller("closeSystemDialogs"); 3711 3712 final int pid = Binder.getCallingPid(); 3713 final int uid = Binder.getCallingUid(); 3714 final long origId = Binder.clearCallingIdentity(); 3715 try { 3716 synchronized (this) { 3717 // Only allow this from foreground processes, so that background 3718 // applications can't abuse it to prevent system UI from being shown. 3719 if (uid >= Process.FIRST_APPLICATION_UID) { 3720 ProcessRecord proc; 3721 synchronized (mPidsSelfLocked) { 3722 proc = mPidsSelfLocked.get(pid); 3723 } 3724 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 3725 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason 3726 + " from background process " + proc); 3727 return; 3728 } 3729 } 3730 closeSystemDialogsLocked(reason); 3731 } 3732 } finally { 3733 Binder.restoreCallingIdentity(origId); 3734 } 3735 } 3736 3737 void closeSystemDialogsLocked(String reason) { 3738 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 3739 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 3740 | Intent.FLAG_RECEIVER_FOREGROUND); 3741 if (reason != null) { 3742 intent.putExtra("reason", reason); 3743 } 3744 mWindowManager.closeSystemDialogs(reason); 3745 3746 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) { 3747 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 3748 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) { 3749 r.stack.finishActivityLocked(r, i, 3750 Activity.RESULT_CANCELED, null, "close-sys", true); 3751 } 3752 } 3753 3754 broadcastIntentLocked(null, null, intent, null, 3755 null, 0, null, null, null, AppOpsManager.OP_NONE, false, false, -1, 3756 Process.SYSTEM_UID, UserHandle.USER_ALL); 3757 } 3758 3759 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) 3760 throws RemoteException { 3761 enforceNotIsolatedCaller("getProcessMemoryInfo"); 3762 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 3763 for (int i=pids.length-1; i>=0; i--) { 3764 infos[i] = new Debug.MemoryInfo(); 3765 Debug.getMemoryInfo(pids[i], infos[i]); 3766 } 3767 return infos; 3768 } 3769 3770 public long[] getProcessPss(int[] pids) throws RemoteException { 3771 enforceNotIsolatedCaller("getProcessPss"); 3772 long[] pss = new long[pids.length]; 3773 for (int i=pids.length-1; i>=0; i--) { 3774 pss[i] = Debug.getPss(pids[i]); 3775 } 3776 return pss; 3777 } 3778 3779 public void killApplicationProcess(String processName, int uid) { 3780 if (processName == null) { 3781 return; 3782 } 3783 3784 int callerUid = Binder.getCallingUid(); 3785 // Only the system server can kill an application 3786 if (callerUid == Process.SYSTEM_UID) { 3787 synchronized (this) { 3788 ProcessRecord app = getProcessRecordLocked(processName, uid); 3789 if (app != null && app.thread != null) { 3790 try { 3791 app.thread.scheduleSuicide(); 3792 } catch (RemoteException e) { 3793 // If the other end already died, then our work here is done. 3794 } 3795 } else { 3796 Slog.w(TAG, "Process/uid not found attempting kill of " 3797 + processName + " / " + uid); 3798 } 3799 } 3800 } else { 3801 throw new SecurityException(callerUid + " cannot kill app process: " + 3802 processName); 3803 } 3804 } 3805 3806 private void forceStopPackageLocked(final String packageName, int uid) { 3807 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 3808 false, true, false, UserHandle.getUserId(uid)); 3809 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 3810 Uri.fromParts("package", packageName, null)); 3811 if (!mProcessesReady) { 3812 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 3813 | Intent.FLAG_RECEIVER_FOREGROUND); 3814 } 3815 intent.putExtra(Intent.EXTRA_UID, uid); 3816 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 3817 broadcastIntentLocked(null, null, intent, 3818 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 3819 false, false, 3820 MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid)); 3821 } 3822 3823 private void forceStopUserLocked(int userId) { 3824 forceStopPackageLocked(null, -1, false, false, true, false, userId); 3825 Intent intent = new Intent(Intent.ACTION_USER_STOPPED); 3826 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 3827 | Intent.FLAG_RECEIVER_FOREGROUND); 3828 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 3829 broadcastIntentLocked(null, null, intent, 3830 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 3831 false, false, 3832 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 3833 } 3834 3835 private final boolean killPackageProcessesLocked(String packageName, int appId, 3836 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, 3837 boolean doit, boolean evenPersistent, String reason) { 3838 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 3839 3840 // Remove all processes this package may have touched: all with the 3841 // same UID (except for the system or root user), and all whose name 3842 // matches the package name. 3843 final String procNamePrefix = packageName != null ? (packageName + ":") : null; 3844 for (SparseArray<ProcessRecord> apps : mProcessNames.getMap().values()) { 3845 final int NA = apps.size(); 3846 for (int ia=0; ia<NA; ia++) { 3847 ProcessRecord app = apps.valueAt(ia); 3848 if (app.persistent && !evenPersistent) { 3849 // we don't kill persistent processes 3850 continue; 3851 } 3852 if (app.removed) { 3853 if (doit) { 3854 procs.add(app); 3855 } 3856 continue; 3857 } 3858 3859 // Skip process if it doesn't meet our oom adj requirement. 3860 if (app.setAdj < minOomAdj) { 3861 continue; 3862 } 3863 3864 // If no package is specified, we call all processes under the 3865 // give user id. 3866 if (packageName == null) { 3867 if (app.userId != userId) { 3868 continue; 3869 } 3870 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) { 3871 continue; 3872 } 3873 // Package has been specified, we want to hit all processes 3874 // that match it. We need to qualify this by the processes 3875 // that are running under the specified app and user ID. 3876 } else { 3877 if (UserHandle.getAppId(app.uid) != appId) { 3878 continue; 3879 } 3880 if (userId != UserHandle.USER_ALL && app.userId != userId) { 3881 continue; 3882 } 3883 if (!app.pkgList.contains(packageName)) { 3884 continue; 3885 } 3886 } 3887 3888 // Process has passed all conditions, kill it! 3889 if (!doit) { 3890 return true; 3891 } 3892 app.removed = true; 3893 procs.add(app); 3894 } 3895 } 3896 3897 int N = procs.size(); 3898 for (int i=0; i<N; i++) { 3899 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason); 3900 } 3901 return N > 0; 3902 } 3903 3904 private final boolean forceStopPackageLocked(String name, int appId, 3905 boolean callerWillRestart, boolean purgeCache, boolean doit, 3906 boolean evenPersistent, int userId) { 3907 int i; 3908 int N; 3909 3910 if (userId == UserHandle.USER_ALL && name == null) { 3911 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 3912 } 3913 3914 if (appId < 0 && name != null) { 3915 try { 3916 appId = UserHandle.getAppId( 3917 AppGlobals.getPackageManager().getPackageUid(name, 0)); 3918 } catch (RemoteException e) { 3919 } 3920 } 3921 3922 if (doit) { 3923 if (name != null) { 3924 Slog.i(TAG, "Force stopping package " + name + " appid=" + appId 3925 + " user=" + userId); 3926 } else { 3927 Slog.i(TAG, "Force stopping user " + userId); 3928 } 3929 3930 Iterator<SparseArray<Long>> badApps = mProcessCrashTimes.getMap().values().iterator(); 3931 while (badApps.hasNext()) { 3932 SparseArray<Long> ba = badApps.next(); 3933 for (i=ba.size()-1; i>=0; i--) { 3934 boolean remove = false; 3935 final int entUid = ba.keyAt(i); 3936 if (name != null) { 3937 if (userId == UserHandle.USER_ALL) { 3938 if (UserHandle.getAppId(entUid) == appId) { 3939 remove = true; 3940 } 3941 } else { 3942 if (entUid == UserHandle.getUid(userId, appId)) { 3943 remove = true; 3944 } 3945 } 3946 } else if (UserHandle.getUserId(entUid) == userId) { 3947 remove = true; 3948 } 3949 if (remove) { 3950 ba.removeAt(i); 3951 } 3952 } 3953 if (ba.size() == 0) { 3954 badApps.remove(); 3955 } 3956 } 3957 } 3958 3959 boolean didSomething = killPackageProcessesLocked(name, appId, userId, 3960 -100, callerWillRestart, true, doit, evenPersistent, 3961 name == null ? ("force stop user " + userId) : ("force stop " + name)); 3962 3963 TaskRecord lastTask = null; 3964 for (i=0; i<mMainStack.mHistory.size(); i++) { 3965 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 3966 final boolean samePackage = r.packageName.equals(name) 3967 || (name == null && r.userId == userId); 3968 if ((userId == UserHandle.USER_ALL || r.userId == userId) 3969 && (samePackage || r.task == lastTask) 3970 && (r.app == null || evenPersistent || !r.app.persistent)) { 3971 if (!doit) { 3972 if (r.finishing) { 3973 // If this activity is just finishing, then it is not 3974 // interesting as far as something to stop. 3975 continue; 3976 } 3977 return true; 3978 } 3979 didSomething = true; 3980 Slog.i(TAG, " Force finishing activity " + r); 3981 if (samePackage) { 3982 if (r.app != null) { 3983 r.app.removed = true; 3984 } 3985 r.app = null; 3986 } 3987 lastTask = r.task; 3988 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED, 3989 null, "force-stop", true)) { 3990 i--; 3991 } 3992 } 3993 } 3994 3995 if (mServices.forceStopLocked(name, userId, evenPersistent, doit)) { 3996 if (!doit) { 3997 return true; 3998 } 3999 didSomething = true; 4000 } 4001 4002 if (name == null) { 4003 // Remove all sticky broadcasts from this user. 4004 mStickyBroadcasts.remove(userId); 4005 } 4006 4007 ArrayList<ContentProviderRecord> providers = new ArrayList<ContentProviderRecord>(); 4008 if (mProviderMap.collectForceStopProviders(name, appId, doit, evenPersistent, 4009 userId, providers)) { 4010 if (!doit) { 4011 return true; 4012 } 4013 didSomething = true; 4014 } 4015 N = providers.size(); 4016 for (i=0; i<N; i++) { 4017 removeDyingProviderLocked(null, providers.get(i), true); 4018 } 4019 4020 if (name == null) { 4021 // Remove pending intents. For now we only do this when force 4022 // stopping users, because we have some problems when doing this 4023 // for packages -- app widgets are not currently cleaned up for 4024 // such packages, so they can be left with bad pending intents. 4025 if (mIntentSenderRecords.size() > 0) { 4026 Iterator<WeakReference<PendingIntentRecord>> it 4027 = mIntentSenderRecords.values().iterator(); 4028 while (it.hasNext()) { 4029 WeakReference<PendingIntentRecord> wpir = it.next(); 4030 if (wpir == null) { 4031 it.remove(); 4032 continue; 4033 } 4034 PendingIntentRecord pir = wpir.get(); 4035 if (pir == null) { 4036 it.remove(); 4037 continue; 4038 } 4039 if (name == null) { 4040 // Stopping user, remove all objects for the user. 4041 if (pir.key.userId != userId) { 4042 // Not the same user, skip it. 4043 continue; 4044 } 4045 } else { 4046 if (UserHandle.getAppId(pir.uid) != appId) { 4047 // Different app id, skip it. 4048 continue; 4049 } 4050 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) { 4051 // Different user, skip it. 4052 continue; 4053 } 4054 if (!pir.key.packageName.equals(name)) { 4055 // Different package, skip it. 4056 continue; 4057 } 4058 } 4059 if (!doit) { 4060 return true; 4061 } 4062 didSomething = true; 4063 it.remove(); 4064 pir.canceled = true; 4065 if (pir.key.activity != null) { 4066 pir.key.activity.pendingResults.remove(pir.ref); 4067 } 4068 } 4069 } 4070 } 4071 4072 if (doit) { 4073 if (purgeCache && name != null) { 4074 AttributeCache ac = AttributeCache.instance(); 4075 if (ac != null) { 4076 ac.removePackage(name); 4077 } 4078 } 4079 if (mBooted) { 4080 mMainStack.resumeTopActivityLocked(null); 4081 mMainStack.scheduleIdleLocked(); 4082 } 4083 } 4084 4085 return didSomething; 4086 } 4087 4088 private final boolean removeProcessLocked(ProcessRecord app, 4089 boolean callerWillRestart, boolean allowRestart, String reason) { 4090 final String name = app.processName; 4091 final int uid = app.uid; 4092 if (DEBUG_PROCESSES) Slog.d( 4093 TAG, "Force removing proc " + app.toShortString() + " (" + name 4094 + "/" + uid + ")"); 4095 4096 mProcessNames.remove(name, uid); 4097 mIsolatedProcesses.remove(app.uid); 4098 if (mHeavyWeightProcess == app) { 4099 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 4100 mHeavyWeightProcess.userId, 0)); 4101 mHeavyWeightProcess = null; 4102 } 4103 boolean needRestart = false; 4104 if (app.pid > 0 && app.pid != MY_PID) { 4105 int pid = app.pid; 4106 synchronized (mPidsSelfLocked) { 4107 mPidsSelfLocked.remove(pid); 4108 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4109 } 4110 Slog.i(TAG, "Killing proc " + app.toShortString() + ": " + reason); 4111 handleAppDiedLocked(app, true, allowRestart); 4112 mLruProcesses.remove(app); 4113 Process.killProcessQuiet(pid); 4114 4115 if (app.persistent && !app.isolated) { 4116 if (!callerWillRestart) { 4117 addAppLocked(app.info, false); 4118 } else { 4119 needRestart = true; 4120 } 4121 } 4122 } else { 4123 mRemovedProcesses.add(app); 4124 } 4125 4126 return needRestart; 4127 } 4128 4129 private final void processStartTimedOutLocked(ProcessRecord app) { 4130 final int pid = app.pid; 4131 boolean gone = false; 4132 synchronized (mPidsSelfLocked) { 4133 ProcessRecord knownApp = mPidsSelfLocked.get(pid); 4134 if (knownApp != null && knownApp.thread == null) { 4135 mPidsSelfLocked.remove(pid); 4136 gone = true; 4137 } 4138 } 4139 4140 if (gone) { 4141 Slog.w(TAG, "Process " + app + " failed to attach"); 4142 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId, 4143 pid, app.uid, app.processName); 4144 mProcessNames.remove(app.processName, app.uid); 4145 mIsolatedProcesses.remove(app.uid); 4146 if (mHeavyWeightProcess == app) { 4147 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 4148 mHeavyWeightProcess.userId, 0)); 4149 mHeavyWeightProcess = null; 4150 } 4151 // Take care of any launching providers waiting for this process. 4152 checkAppInLaunchingProvidersLocked(app, true); 4153 // Take care of any services that are waiting for the process. 4154 mServices.processStartTimedOutLocked(app); 4155 EventLog.writeEvent(EventLogTags.AM_KILL, app.userId, pid, 4156 app.processName, app.setAdj, "start timeout"); 4157 Process.killProcessQuiet(pid); 4158 if (mBackupTarget != null && mBackupTarget.app.pid == pid) { 4159 Slog.w(TAG, "Unattached app died before backup, skipping"); 4160 try { 4161 IBackupManager bm = IBackupManager.Stub.asInterface( 4162 ServiceManager.getService(Context.BACKUP_SERVICE)); 4163 bm.agentDisconnected(app.info.packageName); 4164 } catch (RemoteException e) { 4165 // Can't happen; the backup manager is local 4166 } 4167 } 4168 if (isPendingBroadcastProcessLocked(pid)) { 4169 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 4170 skipPendingBroadcastLocked(pid); 4171 } 4172 } else { 4173 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 4174 } 4175 } 4176 4177 private final boolean attachApplicationLocked(IApplicationThread thread, 4178 int pid) { 4179 4180 // Find the application record that is being attached... either via 4181 // the pid if we are running in multiple processes, or just pull the 4182 // next app record if we are emulating process with anonymous threads. 4183 ProcessRecord app; 4184 if (pid != MY_PID && pid >= 0) { 4185 synchronized (mPidsSelfLocked) { 4186 app = mPidsSelfLocked.get(pid); 4187 } 4188 } else { 4189 app = null; 4190 } 4191 4192 if (app == null) { 4193 Slog.w(TAG, "No pending application record for pid " + pid 4194 + " (IApplicationThread " + thread + "); dropping process"); 4195 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); 4196 if (pid > 0 && pid != MY_PID) { 4197 Process.killProcessQuiet(pid); 4198 } else { 4199 try { 4200 thread.scheduleExit(); 4201 } catch (Exception e) { 4202 // Ignore exceptions. 4203 } 4204 } 4205 return false; 4206 } 4207 4208 // If this application record is still attached to a previous 4209 // process, clean it up now. 4210 if (app.thread != null) { 4211 handleAppDiedLocked(app, true, true); 4212 } 4213 4214 // Tell the process all about itself. 4215 4216 if (localLOGV) Slog.v( 4217 TAG, "Binding process pid " + pid + " to record " + app); 4218 4219 String processName = app.processName; 4220 try { 4221 AppDeathRecipient adr = new AppDeathRecipient( 4222 app, pid, thread); 4223 thread.asBinder().linkToDeath(adr, 0); 4224 app.deathRecipient = adr; 4225 } catch (RemoteException e) { 4226 app.resetPackageList(); 4227 startProcessLocked(app, "link fail", processName); 4228 return false; 4229 } 4230 4231 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName); 4232 4233 app.thread = thread; 4234 app.curAdj = app.setAdj = -100; 4235 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT; 4236 app.setSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 4237 app.forcingToForeground = null; 4238 app.foregroundServices = false; 4239 app.hasShownUi = false; 4240 app.debugging = false; 4241 4242 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 4243 4244 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 4245 List providers = normalMode ? generateApplicationProvidersLocked(app) : null; 4246 4247 if (!normalMode) { 4248 Slog.i(TAG, "Launching preboot mode app: " + app); 4249 } 4250 4251 if (localLOGV) Slog.v( 4252 TAG, "New app record " + app 4253 + " thread=" + thread.asBinder() + " pid=" + pid); 4254 try { 4255 int testMode = IApplicationThread.DEBUG_OFF; 4256 if (mDebugApp != null && mDebugApp.equals(processName)) { 4257 testMode = mWaitForDebugger 4258 ? IApplicationThread.DEBUG_WAIT 4259 : IApplicationThread.DEBUG_ON; 4260 app.debugging = true; 4261 if (mDebugTransient) { 4262 mDebugApp = mOrigDebugApp; 4263 mWaitForDebugger = mOrigWaitForDebugger; 4264 } 4265 } 4266 String profileFile = app.instrumentationProfileFile; 4267 ParcelFileDescriptor profileFd = null; 4268 boolean profileAutoStop = false; 4269 if (mProfileApp != null && mProfileApp.equals(processName)) { 4270 mProfileProc = app; 4271 profileFile = mProfileFile; 4272 profileFd = mProfileFd; 4273 profileAutoStop = mAutoStopProfiler; 4274 } 4275 boolean enableOpenGlTrace = false; 4276 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) { 4277 enableOpenGlTrace = true; 4278 mOpenGlTraceApp = null; 4279 } 4280 4281 // If the app is being launched for restore or full backup, set it up specially 4282 boolean isRestrictedBackupMode = false; 4283 if (mBackupTarget != null && mBackupAppName.equals(processName)) { 4284 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE) 4285 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL) 4286 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL); 4287 } 4288 4289 ensurePackageDexOpt(app.instrumentationInfo != null 4290 ? app.instrumentationInfo.packageName 4291 : app.info.packageName); 4292 if (app.instrumentationClass != null) { 4293 ensurePackageDexOpt(app.instrumentationClass.getPackageName()); 4294 } 4295 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Binding proc " 4296 + processName + " with config " + mConfiguration); 4297 ApplicationInfo appInfo = app.instrumentationInfo != null 4298 ? app.instrumentationInfo : app.info; 4299 app.compat = compatibilityInfoForPackageLocked(appInfo); 4300 if (profileFd != null) { 4301 profileFd = profileFd.dup(); 4302 } 4303 thread.bindApplication(processName, appInfo, providers, 4304 app.instrumentationClass, profileFile, profileFd, profileAutoStop, 4305 app.instrumentationArguments, app.instrumentationWatcher, 4306 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace, 4307 isRestrictedBackupMode || !normalMode, app.persistent, 4308 new Configuration(mConfiguration), app.compat, getCommonServicesLocked(), 4309 mCoreSettingsObserver.getCoreSettingsLocked()); 4310 updateLruProcessLocked(app, false); 4311 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); 4312 } catch (Exception e) { 4313 // todo: Yikes! What should we do? For now we will try to 4314 // start another process, but that could easily get us in 4315 // an infinite loop of restarting processes... 4316 Slog.w(TAG, "Exception thrown during bind!", e); 4317 4318 app.resetPackageList(); 4319 app.unlinkDeathRecipient(); 4320 startProcessLocked(app, "bind fail", processName); 4321 return false; 4322 } 4323 4324 // Remove this record from the list of starting applications. 4325 mPersistentStartingProcesses.remove(app); 4326 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG, 4327 "Attach application locked removing on hold: " + app); 4328 mProcessesOnHold.remove(app); 4329 4330 boolean badApp = false; 4331 boolean didSomething = false; 4332 4333 // See if the top visible activity is waiting to run in this process... 4334 ActivityRecord hr = mMainStack.topRunningActivityLocked(null); 4335 if (hr != null && normalMode) { 4336 if (hr.app == null && app.uid == hr.info.applicationInfo.uid 4337 && processName.equals(hr.processName)) { 4338 try { 4339 if (mHeadless) { 4340 Slog.e(TAG, "Starting activities not supported on headless device: " + hr); 4341 } else if (mMainStack.realStartActivityLocked(hr, app, true, true)) { 4342 didSomething = true; 4343 } 4344 } catch (Exception e) { 4345 Slog.w(TAG, "Exception in new application when starting activity " 4346 + hr.intent.getComponent().flattenToShortString(), e); 4347 badApp = true; 4348 } 4349 } else { 4350 mMainStack.ensureActivitiesVisibleLocked(hr, null, processName, 0); 4351 } 4352 } 4353 4354 // Find any services that should be running in this process... 4355 if (!badApp) { 4356 try { 4357 didSomething |= mServices.attachApplicationLocked(app, processName); 4358 } catch (Exception e) { 4359 badApp = true; 4360 } 4361 } 4362 4363 // Check if a next-broadcast receiver is in this process... 4364 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 4365 try { 4366 didSomething = sendPendingBroadcastsLocked(app); 4367 } catch (Exception e) { 4368 // If the app died trying to launch the receiver we declare it 'bad' 4369 badApp = true; 4370 } 4371 } 4372 4373 // Check whether the next backup agent is in this process... 4374 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) { 4375 if (DEBUG_BACKUP) Slog.v(TAG, "New app is backup target, launching agent for " + app); 4376 ensurePackageDexOpt(mBackupTarget.appInfo.packageName); 4377 try { 4378 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, 4379 compatibilityInfoForPackageLocked(mBackupTarget.appInfo), 4380 mBackupTarget.backupMode); 4381 } catch (Exception e) { 4382 Slog.w(TAG, "Exception scheduling backup agent creation: "); 4383 e.printStackTrace(); 4384 } 4385 } 4386 4387 if (badApp) { 4388 // todo: Also need to kill application to deal with all 4389 // kinds of exceptions. 4390 handleAppDiedLocked(app, false, true); 4391 return false; 4392 } 4393 4394 if (!didSomething) { 4395 updateOomAdjLocked(); 4396 } 4397 4398 return true; 4399 } 4400 4401 public final void attachApplication(IApplicationThread thread) { 4402 synchronized (this) { 4403 int callingPid = Binder.getCallingPid(); 4404 final long origId = Binder.clearCallingIdentity(); 4405 attachApplicationLocked(thread, callingPid); 4406 Binder.restoreCallingIdentity(origId); 4407 } 4408 } 4409 4410 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { 4411 final long origId = Binder.clearCallingIdentity(); 4412 ActivityRecord r = mMainStack.activityIdleInternal(token, false, config); 4413 if (stopProfiling) { 4414 synchronized (this) { 4415 if (mProfileProc == r.app) { 4416 if (mProfileFd != null) { 4417 try { 4418 mProfileFd.close(); 4419 } catch (IOException e) { 4420 } 4421 clearProfilerLocked(); 4422 } 4423 } 4424 } 4425 } 4426 Binder.restoreCallingIdentity(origId); 4427 } 4428 4429 void enableScreenAfterBoot() { 4430 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN, 4431 SystemClock.uptimeMillis()); 4432 mWindowManager.enableScreenAfterBoot(); 4433 4434 synchronized (this) { 4435 updateEventDispatchingLocked(); 4436 } 4437 } 4438 4439 public void showBootMessage(final CharSequence msg, final boolean always) { 4440 enforceNotIsolatedCaller("showBootMessage"); 4441 mWindowManager.showBootMessage(msg, always); 4442 } 4443 4444 public void dismissKeyguardOnNextActivity() { 4445 enforceNotIsolatedCaller("dismissKeyguardOnNextActivity"); 4446 final long token = Binder.clearCallingIdentity(); 4447 try { 4448 synchronized (this) { 4449 if (mLockScreenShown) { 4450 mLockScreenShown = false; 4451 comeOutOfSleepIfNeededLocked(); 4452 } 4453 mMainStack.dismissKeyguardOnNextActivityLocked(); 4454 } 4455 } finally { 4456 Binder.restoreCallingIdentity(token); 4457 } 4458 } 4459 4460 final void finishBooting() { 4461 IntentFilter pkgFilter = new IntentFilter(); 4462 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 4463 pkgFilter.addDataScheme("package"); 4464 mContext.registerReceiver(new BroadcastReceiver() { 4465 @Override 4466 public void onReceive(Context context, Intent intent) { 4467 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 4468 if (pkgs != null) { 4469 for (String pkg : pkgs) { 4470 synchronized (ActivityManagerService.this) { 4471 if (forceStopPackageLocked(pkg, -1, false, false, false, false, 0)) { 4472 setResultCode(Activity.RESULT_OK); 4473 return; 4474 } 4475 } 4476 } 4477 } 4478 } 4479 }, pkgFilter); 4480 4481 synchronized (this) { 4482 // Ensure that any processes we had put on hold are now started 4483 // up. 4484 final int NP = mProcessesOnHold.size(); 4485 if (NP > 0) { 4486 ArrayList<ProcessRecord> procs = 4487 new ArrayList<ProcessRecord>(mProcessesOnHold); 4488 for (int ip=0; ip<NP; ip++) { 4489 if (DEBUG_PROCESSES) Slog.v(TAG, "Starting process on hold: " 4490 + procs.get(ip)); 4491 startProcessLocked(procs.get(ip), "on-hold", null); 4492 } 4493 } 4494 4495 if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) { 4496 // Start looking for apps that are abusing wake locks. 4497 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 4498 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 4499 // Tell anyone interested that we are done booting! 4500 SystemProperties.set("sys.boot_completed", "1"); 4501 SystemProperties.set("dev.bootcomplete", "1"); 4502 for (int i=0; i<mStartedUsers.size(); i++) { 4503 UserStartedState uss = mStartedUsers.valueAt(i); 4504 if (uss.mState == UserStartedState.STATE_BOOTING) { 4505 uss.mState = UserStartedState.STATE_RUNNING; 4506 final int userId = mStartedUsers.keyAt(i); 4507 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 4508 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 4509 broadcastIntentLocked(null, null, intent, 4510 null, null, 0, null, null, 4511 android.Manifest.permission.RECEIVE_BOOT_COMPLETED, 4512 AppOpsManager.OP_NONE, false, false, MY_PID, Process.SYSTEM_UID, 4513 userId); 4514 } 4515 } 4516 } 4517 } 4518 } 4519 4520 final void ensureBootCompleted() { 4521 boolean booting; 4522 boolean enableScreen; 4523 synchronized (this) { 4524 booting = mBooting; 4525 mBooting = false; 4526 enableScreen = !mBooted; 4527 mBooted = true; 4528 } 4529 4530 if (booting) { 4531 finishBooting(); 4532 } 4533 4534 if (enableScreen) { 4535 enableScreenAfterBoot(); 4536 } 4537 } 4538 4539 public final void activityResumed(IBinder token) { 4540 final long origId = Binder.clearCallingIdentity(); 4541 mMainStack.activityResumed(token); 4542 Binder.restoreCallingIdentity(origId); 4543 } 4544 4545 public final void activityPaused(IBinder token) { 4546 final long origId = Binder.clearCallingIdentity(); 4547 mMainStack.activityPaused(token, false); 4548 Binder.restoreCallingIdentity(origId); 4549 } 4550 4551 public final void activityStopped(IBinder token, Bundle icicle, Bitmap thumbnail, 4552 CharSequence description) { 4553 if (localLOGV) Slog.v( 4554 TAG, "Activity stopped: token=" + token); 4555 4556 // Refuse possible leaked file descriptors 4557 if (icicle != null && icicle.hasFileDescriptors()) { 4558 throw new IllegalArgumentException("File descriptors passed in Bundle"); 4559 } 4560 4561 ActivityRecord r = null; 4562 4563 final long origId = Binder.clearCallingIdentity(); 4564 4565 synchronized (this) { 4566 r = mMainStack.isInStackLocked(token); 4567 if (r != null) { 4568 r.stack.activityStoppedLocked(r, icicle, thumbnail, description); 4569 } 4570 } 4571 4572 if (r != null) { 4573 sendPendingThumbnail(r, null, null, null, false); 4574 } 4575 4576 trimApplications(); 4577 4578 Binder.restoreCallingIdentity(origId); 4579 } 4580 4581 public final void activityDestroyed(IBinder token) { 4582 if (DEBUG_SWITCH) Slog.v(TAG, "ACTIVITY DESTROYED: " + token); 4583 mMainStack.activityDestroyed(token); 4584 } 4585 4586 public String getCallingPackage(IBinder token) { 4587 synchronized (this) { 4588 ActivityRecord r = getCallingRecordLocked(token); 4589 return r != null ? r.info.packageName : null; 4590 } 4591 } 4592 4593 public ComponentName getCallingActivity(IBinder token) { 4594 synchronized (this) { 4595 ActivityRecord r = getCallingRecordLocked(token); 4596 return r != null ? r.intent.getComponent() : null; 4597 } 4598 } 4599 4600 private ActivityRecord getCallingRecordLocked(IBinder token) { 4601 ActivityRecord r = mMainStack.isInStackLocked(token); 4602 if (r == null) { 4603 return null; 4604 } 4605 return r.resultTo; 4606 } 4607 4608 public ComponentName getActivityClassForToken(IBinder token) { 4609 synchronized(this) { 4610 ActivityRecord r = mMainStack.isInStackLocked(token); 4611 if (r == null) { 4612 return null; 4613 } 4614 return r.intent.getComponent(); 4615 } 4616 } 4617 4618 public String getPackageForToken(IBinder token) { 4619 synchronized(this) { 4620 ActivityRecord r = mMainStack.isInStackLocked(token); 4621 if (r == null) { 4622 return null; 4623 } 4624 return r.packageName; 4625 } 4626 } 4627 4628 public IIntentSender getIntentSender(int type, 4629 String packageName, IBinder token, String resultWho, 4630 int requestCode, Intent[] intents, String[] resolvedTypes, 4631 int flags, Bundle options, int userId) { 4632 enforceNotIsolatedCaller("getIntentSender"); 4633 // Refuse possible leaked file descriptors 4634 if (intents != null) { 4635 if (intents.length < 1) { 4636 throw new IllegalArgumentException("Intents array length must be >= 1"); 4637 } 4638 for (int i=0; i<intents.length; i++) { 4639 Intent intent = intents[i]; 4640 if (intent != null) { 4641 if (intent.hasFileDescriptors()) { 4642 throw new IllegalArgumentException("File descriptors passed in Intent"); 4643 } 4644 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 4645 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 4646 throw new IllegalArgumentException( 4647 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 4648 } 4649 intents[i] = new Intent(intent); 4650 } 4651 } 4652 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 4653 throw new IllegalArgumentException( 4654 "Intent array length does not match resolvedTypes length"); 4655 } 4656 } 4657 if (options != null) { 4658 if (options.hasFileDescriptors()) { 4659 throw new IllegalArgumentException("File descriptors passed in options"); 4660 } 4661 } 4662 4663 synchronized(this) { 4664 int callingUid = Binder.getCallingUid(); 4665 int origUserId = userId; 4666 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 4667 type == ActivityManager.INTENT_SENDER_BROADCAST, false, 4668 "getIntentSender", null); 4669 if (origUserId == UserHandle.USER_CURRENT) { 4670 // We don't want to evaluate this until the pending intent is 4671 // actually executed. However, we do want to always do the 4672 // security checking for it above. 4673 userId = UserHandle.USER_CURRENT; 4674 } 4675 try { 4676 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 4677 int uid = AppGlobals.getPackageManager() 4678 .getPackageUid(packageName, UserHandle.getUserId(callingUid)); 4679 if (!UserHandle.isSameApp(callingUid, uid)) { 4680 String msg = "Permission Denial: getIntentSender() from pid=" 4681 + Binder.getCallingPid() 4682 + ", uid=" + Binder.getCallingUid() 4683 + ", (need uid=" + uid + ")" 4684 + " is not allowed to send as package " + packageName; 4685 Slog.w(TAG, msg); 4686 throw new SecurityException(msg); 4687 } 4688 } 4689 4690 return getIntentSenderLocked(type, packageName, callingUid, userId, 4691 token, resultWho, requestCode, intents, resolvedTypes, flags, options); 4692 4693 } catch (RemoteException e) { 4694 throw new SecurityException(e); 4695 } 4696 } 4697 } 4698 4699 IIntentSender getIntentSenderLocked(int type, String packageName, 4700 int callingUid, int userId, IBinder token, String resultWho, 4701 int requestCode, Intent[] intents, String[] resolvedTypes, int flags, 4702 Bundle options) { 4703 if (DEBUG_MU) 4704 Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid); 4705 ActivityRecord activity = null; 4706 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 4707 activity = mMainStack.isInStackLocked(token); 4708 if (activity == null) { 4709 return null; 4710 } 4711 if (activity.finishing) { 4712 return null; 4713 } 4714 } 4715 4716 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0; 4717 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0; 4718 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0; 4719 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT 4720 |PendingIntent.FLAG_UPDATE_CURRENT); 4721 4722 PendingIntentRecord.Key key = new PendingIntentRecord.Key( 4723 type, packageName, activity, resultWho, 4724 requestCode, intents, resolvedTypes, flags, options, userId); 4725 WeakReference<PendingIntentRecord> ref; 4726 ref = mIntentSenderRecords.get(key); 4727 PendingIntentRecord rec = ref != null ? ref.get() : null; 4728 if (rec != null) { 4729 if (!cancelCurrent) { 4730 if (updateCurrent) { 4731 if (rec.key.requestIntent != null) { 4732 rec.key.requestIntent.replaceExtras(intents != null ? 4733 intents[intents.length - 1] : null); 4734 } 4735 if (intents != null) { 4736 intents[intents.length-1] = rec.key.requestIntent; 4737 rec.key.allIntents = intents; 4738 rec.key.allResolvedTypes = resolvedTypes; 4739 } else { 4740 rec.key.allIntents = null; 4741 rec.key.allResolvedTypes = null; 4742 } 4743 } 4744 return rec; 4745 } 4746 rec.canceled = true; 4747 mIntentSenderRecords.remove(key); 4748 } 4749 if (noCreate) { 4750 return rec; 4751 } 4752 rec = new PendingIntentRecord(this, key, callingUid); 4753 mIntentSenderRecords.put(key, rec.ref); 4754 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 4755 if (activity.pendingResults == null) { 4756 activity.pendingResults 4757 = new HashSet<WeakReference<PendingIntentRecord>>(); 4758 } 4759 activity.pendingResults.add(rec.ref); 4760 } 4761 return rec; 4762 } 4763 4764 public void cancelIntentSender(IIntentSender sender) { 4765 if (!(sender instanceof PendingIntentRecord)) { 4766 return; 4767 } 4768 synchronized(this) { 4769 PendingIntentRecord rec = (PendingIntentRecord)sender; 4770 try { 4771 int uid = AppGlobals.getPackageManager() 4772 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId()); 4773 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) { 4774 String msg = "Permission Denial: cancelIntentSender() from pid=" 4775 + Binder.getCallingPid() 4776 + ", uid=" + Binder.getCallingUid() 4777 + " is not allowed to cancel packges " 4778 + rec.key.packageName; 4779 Slog.w(TAG, msg); 4780 throw new SecurityException(msg); 4781 } 4782 } catch (RemoteException e) { 4783 throw new SecurityException(e); 4784 } 4785 cancelIntentSenderLocked(rec, true); 4786 } 4787 } 4788 4789 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) { 4790 rec.canceled = true; 4791 mIntentSenderRecords.remove(rec.key); 4792 if (cleanActivity && rec.key.activity != null) { 4793 rec.key.activity.pendingResults.remove(rec.ref); 4794 } 4795 } 4796 4797 public String getPackageForIntentSender(IIntentSender pendingResult) { 4798 if (!(pendingResult instanceof PendingIntentRecord)) { 4799 return null; 4800 } 4801 try { 4802 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 4803 return res.key.packageName; 4804 } catch (ClassCastException e) { 4805 } 4806 return null; 4807 } 4808 4809 public int getUidForIntentSender(IIntentSender sender) { 4810 if (sender instanceof PendingIntentRecord) { 4811 try { 4812 PendingIntentRecord res = (PendingIntentRecord)sender; 4813 return res.uid; 4814 } catch (ClassCastException e) { 4815 } 4816 } 4817 return -1; 4818 } 4819 4820 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 4821 if (!(pendingResult instanceof PendingIntentRecord)) { 4822 return false; 4823 } 4824 try { 4825 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 4826 if (res.key.allIntents == null) { 4827 return false; 4828 } 4829 for (int i=0; i<res.key.allIntents.length; i++) { 4830 Intent intent = res.key.allIntents[i]; 4831 if (intent.getPackage() != null && intent.getComponent() != null) { 4832 return false; 4833 } 4834 } 4835 return true; 4836 } catch (ClassCastException e) { 4837 } 4838 return false; 4839 } 4840 4841 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 4842 if (!(pendingResult instanceof PendingIntentRecord)) { 4843 return false; 4844 } 4845 try { 4846 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 4847 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 4848 return true; 4849 } 4850 return false; 4851 } catch (ClassCastException e) { 4852 } 4853 return false; 4854 } 4855 4856 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 4857 if (!(pendingResult instanceof PendingIntentRecord)) { 4858 return null; 4859 } 4860 try { 4861 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 4862 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 4863 } catch (ClassCastException e) { 4864 } 4865 return null; 4866 } 4867 4868 public void setProcessLimit(int max) { 4869 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 4870 "setProcessLimit()"); 4871 synchronized (this) { 4872 mProcessLimit = max < 0 ? ProcessList.MAX_HIDDEN_APPS : max; 4873 mProcessLimitOverride = max; 4874 } 4875 trimApplications(); 4876 } 4877 4878 public int getProcessLimit() { 4879 synchronized (this) { 4880 return mProcessLimitOverride; 4881 } 4882 } 4883 4884 void foregroundTokenDied(ForegroundToken token) { 4885 synchronized (ActivityManagerService.this) { 4886 synchronized (mPidsSelfLocked) { 4887 ForegroundToken cur 4888 = mForegroundProcesses.get(token.pid); 4889 if (cur != token) { 4890 return; 4891 } 4892 mForegroundProcesses.remove(token.pid); 4893 ProcessRecord pr = mPidsSelfLocked.get(token.pid); 4894 if (pr == null) { 4895 return; 4896 } 4897 pr.forcingToForeground = null; 4898 pr.foregroundServices = false; 4899 } 4900 updateOomAdjLocked(); 4901 } 4902 } 4903 4904 public void setProcessForeground(IBinder token, int pid, boolean isForeground) { 4905 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 4906 "setProcessForeground()"); 4907 synchronized(this) { 4908 boolean changed = false; 4909 4910 synchronized (mPidsSelfLocked) { 4911 ProcessRecord pr = mPidsSelfLocked.get(pid); 4912 if (pr == null && isForeground) { 4913 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 4914 return; 4915 } 4916 ForegroundToken oldToken = mForegroundProcesses.get(pid); 4917 if (oldToken != null) { 4918 oldToken.token.unlinkToDeath(oldToken, 0); 4919 mForegroundProcesses.remove(pid); 4920 if (pr != null) { 4921 pr.forcingToForeground = null; 4922 } 4923 changed = true; 4924 } 4925 if (isForeground && token != null) { 4926 ForegroundToken newToken = new ForegroundToken() { 4927 public void binderDied() { 4928 foregroundTokenDied(this); 4929 } 4930 }; 4931 newToken.pid = pid; 4932 newToken.token = token; 4933 try { 4934 token.linkToDeath(newToken, 0); 4935 mForegroundProcesses.put(pid, newToken); 4936 pr.forcingToForeground = token; 4937 changed = true; 4938 } catch (RemoteException e) { 4939 // If the process died while doing this, we will later 4940 // do the cleanup with the process death link. 4941 } 4942 } 4943 } 4944 4945 if (changed) { 4946 updateOomAdjLocked(); 4947 } 4948 } 4949 } 4950 4951 // ========================================================= 4952 // PERMISSIONS 4953 // ========================================================= 4954 4955 static class PermissionController extends IPermissionController.Stub { 4956 ActivityManagerService mActivityManagerService; 4957 PermissionController(ActivityManagerService activityManagerService) { 4958 mActivityManagerService = activityManagerService; 4959 } 4960 4961 public boolean checkPermission(String permission, int pid, int uid) { 4962 return mActivityManagerService.checkPermission(permission, pid, 4963 uid) == PackageManager.PERMISSION_GRANTED; 4964 } 4965 } 4966 4967 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 4968 public int checkComponentPermission(String permission, int pid, int uid, 4969 int owningUid, boolean exported) { 4970 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 4971 owningUid, exported); 4972 } 4973 4974 public Object getAMSLock() { 4975 return ActivityManagerService.this; 4976 } 4977 } 4978 4979 /** 4980 * This can be called with or without the global lock held. 4981 */ 4982 int checkComponentPermission(String permission, int pid, int uid, 4983 int owningUid, boolean exported) { 4984 // We might be performing an operation on behalf of an indirect binder 4985 // invocation, e.g. via {@link #openContentUri}. Check and adjust the 4986 // client identity accordingly before proceeding. 4987 Identity tlsIdentity = sCallerIdentity.get(); 4988 if (tlsIdentity != null) { 4989 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {" 4990 + tlsIdentity.pid + "," + tlsIdentity.uid + "}"); 4991 uid = tlsIdentity.uid; 4992 pid = tlsIdentity.pid; 4993 } 4994 4995 if (pid == MY_PID) { 4996 return PackageManager.PERMISSION_GRANTED; 4997 } 4998 4999 return ActivityManager.checkComponentPermission(permission, uid, 5000 owningUid, exported); 5001 } 5002 5003 /** 5004 * As the only public entry point for permissions checking, this method 5005 * can enforce the semantic that requesting a check on a null global 5006 * permission is automatically denied. (Internally a null permission 5007 * string is used when calling {@link #checkComponentPermission} in cases 5008 * when only uid-based security is needed.) 5009 * 5010 * This can be called with or without the global lock held. 5011 */ 5012 public int checkPermission(String permission, int pid, int uid) { 5013 if (permission == null) { 5014 return PackageManager.PERMISSION_DENIED; 5015 } 5016 return checkComponentPermission(permission, pid, UserHandle.getAppId(uid), -1, true); 5017 } 5018 5019 /** 5020 * Binder IPC calls go through the public entry point. 5021 * This can be called with or without the global lock held. 5022 */ 5023 int checkCallingPermission(String permission) { 5024 return checkPermission(permission, 5025 Binder.getCallingPid(), 5026 UserHandle.getAppId(Binder.getCallingUid())); 5027 } 5028 5029 /** 5030 * This can be called with or without the global lock held. 5031 */ 5032 void enforceCallingPermission(String permission, String func) { 5033 if (checkCallingPermission(permission) 5034 == PackageManager.PERMISSION_GRANTED) { 5035 return; 5036 } 5037 5038 String msg = "Permission Denial: " + func + " from pid=" 5039 + Binder.getCallingPid() 5040 + ", uid=" + Binder.getCallingUid() 5041 + " requires " + permission; 5042 Slog.w(TAG, msg); 5043 throw new SecurityException(msg); 5044 } 5045 5046 /** 5047 * Determine if UID is holding permissions required to access {@link Uri} in 5048 * the given {@link ProviderInfo}. Final permission checking is always done 5049 * in {@link ContentProvider}. 5050 */ 5051 private final boolean checkHoldingPermissionsLocked( 5052 IPackageManager pm, ProviderInfo pi, Uri uri, int uid, int modeFlags) { 5053 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5054 "checkHoldingPermissionsLocked: uri=" + uri + " uid=" + uid); 5055 5056 if (pi.applicationInfo.uid == uid) { 5057 return true; 5058 } else if (!pi.exported) { 5059 return false; 5060 } 5061 5062 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0; 5063 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0; 5064 try { 5065 // check if target holds top-level <provider> permissions 5066 if (!readMet && pi.readPermission != null 5067 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) { 5068 readMet = true; 5069 } 5070 if (!writeMet && pi.writePermission != null 5071 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) { 5072 writeMet = true; 5073 } 5074 5075 // track if unprotected read/write is allowed; any denied 5076 // <path-permission> below removes this ability 5077 boolean allowDefaultRead = pi.readPermission == null; 5078 boolean allowDefaultWrite = pi.writePermission == null; 5079 5080 // check if target holds any <path-permission> that match uri 5081 final PathPermission[] pps = pi.pathPermissions; 5082 if (pps != null) { 5083 final String path = uri.getPath(); 5084 int i = pps.length; 5085 while (i > 0 && (!readMet || !writeMet)) { 5086 i--; 5087 PathPermission pp = pps[i]; 5088 if (pp.match(path)) { 5089 if (!readMet) { 5090 final String pprperm = pp.getReadPermission(); 5091 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking read perm for " 5092 + pprperm + " for " + pp.getPath() 5093 + ": match=" + pp.match(path) 5094 + " check=" + pm.checkUidPermission(pprperm, uid)); 5095 if (pprperm != null) { 5096 if (pm.checkUidPermission(pprperm, uid) == PERMISSION_GRANTED) { 5097 readMet = true; 5098 } else { 5099 allowDefaultRead = false; 5100 } 5101 } 5102 } 5103 if (!writeMet) { 5104 final String ppwperm = pp.getWritePermission(); 5105 if (DEBUG_URI_PERMISSION) Slog.v(TAG, "Checking write perm " 5106 + ppwperm + " for " + pp.getPath() 5107 + ": match=" + pp.match(path) 5108 + " check=" + pm.checkUidPermission(ppwperm, uid)); 5109 if (ppwperm != null) { 5110 if (pm.checkUidPermission(ppwperm, uid) == PERMISSION_GRANTED) { 5111 writeMet = true; 5112 } else { 5113 allowDefaultWrite = false; 5114 } 5115 } 5116 } 5117 } 5118 } 5119 } 5120 5121 // grant unprotected <provider> read/write, if not blocked by 5122 // <path-permission> above 5123 if (allowDefaultRead) readMet = true; 5124 if (allowDefaultWrite) writeMet = true; 5125 5126 } catch (RemoteException e) { 5127 return false; 5128 } 5129 5130 return readMet && writeMet; 5131 } 5132 5133 private final boolean checkUriPermissionLocked(Uri uri, int uid, 5134 int modeFlags) { 5135 // Root gets to do everything. 5136 if (uid == 0) { 5137 return true; 5138 } 5139 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(uid); 5140 if (perms == null) return false; 5141 UriPermission perm = perms.get(uri); 5142 if (perm == null) return false; 5143 return (modeFlags&perm.modeFlags) == modeFlags; 5144 } 5145 5146 public int checkUriPermission(Uri uri, int pid, int uid, int modeFlags) { 5147 enforceNotIsolatedCaller("checkUriPermission"); 5148 5149 // Another redirected-binder-call permissions check as in 5150 // {@link checkComponentPermission}. 5151 Identity tlsIdentity = sCallerIdentity.get(); 5152 if (tlsIdentity != null) { 5153 uid = tlsIdentity.uid; 5154 pid = tlsIdentity.pid; 5155 } 5156 5157 // Our own process gets to do everything. 5158 if (pid == MY_PID) { 5159 return PackageManager.PERMISSION_GRANTED; 5160 } 5161 synchronized(this) { 5162 return checkUriPermissionLocked(uri, uid, modeFlags) 5163 ? PackageManager.PERMISSION_GRANTED 5164 : PackageManager.PERMISSION_DENIED; 5165 } 5166 } 5167 5168 /** 5169 * Check if the targetPkg can be granted permission to access uri by 5170 * the callingUid using the given modeFlags. Throws a security exception 5171 * if callingUid is not allowed to do this. Returns the uid of the target 5172 * if the URI permission grant should be performed; returns -1 if it is not 5173 * needed (for example targetPkg already has permission to access the URI). 5174 * If you already know the uid of the target, you can supply it in 5175 * lastTargetUid else set that to -1. 5176 */ 5177 int checkGrantUriPermissionLocked(int callingUid, String targetPkg, 5178 Uri uri, int modeFlags, int lastTargetUid) { 5179 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION 5180 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 5181 if (modeFlags == 0) { 5182 return -1; 5183 } 5184 5185 if (targetPkg != null) { 5186 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5187 "Checking grant " + targetPkg + " permission to " + uri); 5188 } 5189 5190 final IPackageManager pm = AppGlobals.getPackageManager(); 5191 5192 // If this is not a content: uri, we can't do anything with it. 5193 if (!ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) { 5194 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5195 "Can't grant URI permission for non-content URI: " + uri); 5196 return -1; 5197 } 5198 5199 String name = uri.getAuthority(); 5200 ProviderInfo pi = null; 5201 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, 5202 UserHandle.getUserId(callingUid)); 5203 if (cpr != null) { 5204 pi = cpr.info; 5205 } else { 5206 try { 5207 pi = pm.resolveContentProvider(name, 5208 PackageManager.GET_URI_PERMISSION_PATTERNS, 5209 UserHandle.getUserId(callingUid)); 5210 } catch (RemoteException ex) { 5211 } 5212 } 5213 if (pi == null) { 5214 Slog.w(TAG, "No content provider found for permission check: " + uri.toSafeString()); 5215 return -1; 5216 } 5217 5218 int targetUid = lastTargetUid; 5219 if (targetUid < 0 && targetPkg != null) { 5220 try { 5221 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid)); 5222 if (targetUid < 0) { 5223 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5224 "Can't grant URI permission no uid for: " + targetPkg); 5225 return -1; 5226 } 5227 } catch (RemoteException ex) { 5228 return -1; 5229 } 5230 } 5231 5232 if (targetUid >= 0) { 5233 // First... does the target actually need this permission? 5234 if (checkHoldingPermissionsLocked(pm, pi, uri, targetUid, modeFlags)) { 5235 // No need to grant the target this permission. 5236 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5237 "Target " + targetPkg + " already has full permission to " + uri); 5238 return -1; 5239 } 5240 } else { 5241 // First... there is no target package, so can anyone access it? 5242 boolean allowed = pi.exported; 5243 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 5244 if (pi.readPermission != null) { 5245 allowed = false; 5246 } 5247 } 5248 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 5249 if (pi.writePermission != null) { 5250 allowed = false; 5251 } 5252 } 5253 if (allowed) { 5254 return -1; 5255 } 5256 } 5257 5258 // Second... is the provider allowing granting of URI permissions? 5259 if (!pi.grantUriPermissions) { 5260 throw new SecurityException("Provider " + pi.packageName 5261 + "/" + pi.name 5262 + " does not allow granting of Uri permissions (uri " 5263 + uri + ")"); 5264 } 5265 if (pi.uriPermissionPatterns != null) { 5266 final int N = pi.uriPermissionPatterns.length; 5267 boolean allowed = false; 5268 for (int i=0; i<N; i++) { 5269 if (pi.uriPermissionPatterns[i] != null 5270 && pi.uriPermissionPatterns[i].match(uri.getPath())) { 5271 allowed = true; 5272 break; 5273 } 5274 } 5275 if (!allowed) { 5276 throw new SecurityException("Provider " + pi.packageName 5277 + "/" + pi.name 5278 + " does not allow granting of permission to path of Uri " 5279 + uri); 5280 } 5281 } 5282 5283 // Third... does the caller itself have permission to access 5284 // this uri? 5285 if (callingUid != Process.myUid()) { 5286 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) { 5287 if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) { 5288 throw new SecurityException("Uid " + callingUid 5289 + " does not have permission to uri " + uri); 5290 } 5291 } 5292 } 5293 5294 return targetUid; 5295 } 5296 5297 public int checkGrantUriPermission(int callingUid, String targetPkg, 5298 Uri uri, int modeFlags) { 5299 enforceNotIsolatedCaller("checkGrantUriPermission"); 5300 synchronized(this) { 5301 return checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1); 5302 } 5303 } 5304 5305 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, 5306 Uri uri, int modeFlags, UriPermissionOwner owner) { 5307 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION 5308 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 5309 if (modeFlags == 0) { 5310 return; 5311 } 5312 5313 // So here we are: the caller has the assumed permission 5314 // to the uri, and the target doesn't. Let's now give this to 5315 // the target. 5316 5317 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5318 "Granting " + targetPkg + "/" + targetUid + " permission to " + uri); 5319 5320 HashMap<Uri, UriPermission> targetUris 5321 = mGrantedUriPermissions.get(targetUid); 5322 if (targetUris == null) { 5323 targetUris = new HashMap<Uri, UriPermission>(); 5324 mGrantedUriPermissions.put(targetUid, targetUris); 5325 } 5326 5327 UriPermission perm = targetUris.get(uri); 5328 if (perm == null) { 5329 perm = new UriPermission(targetUid, uri); 5330 targetUris.put(uri, perm); 5331 } 5332 5333 perm.modeFlags |= modeFlags; 5334 if (owner == null) { 5335 perm.globalModeFlags |= modeFlags; 5336 } else { 5337 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 5338 perm.readOwners.add(owner); 5339 owner.addReadPermission(perm); 5340 } 5341 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 5342 perm.writeOwners.add(owner); 5343 owner.addWritePermission(perm); 5344 } 5345 } 5346 } 5347 5348 void grantUriPermissionLocked(int callingUid, String targetPkg, Uri uri, 5349 int modeFlags, UriPermissionOwner owner) { 5350 if (targetPkg == null) { 5351 throw new NullPointerException("targetPkg"); 5352 } 5353 5354 int targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, modeFlags, -1); 5355 if (targetUid < 0) { 5356 return; 5357 } 5358 5359 grantUriPermissionUncheckedLocked(targetUid, targetPkg, uri, modeFlags, owner); 5360 } 5361 5362 static class NeededUriGrants extends ArrayList<Uri> { 5363 final String targetPkg; 5364 final int targetUid; 5365 final int flags; 5366 5367 NeededUriGrants(String _targetPkg, int _targetUid, int _flags) { 5368 targetPkg = _targetPkg; 5369 targetUid = _targetUid; 5370 flags = _flags; 5371 } 5372 } 5373 5374 /** 5375 * Like checkGrantUriPermissionLocked, but takes an Intent. 5376 */ 5377 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid, 5378 String targetPkg, Intent intent, int mode, NeededUriGrants needed) { 5379 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5380 "Checking URI perm to data=" + (intent != null ? intent.getData() : null) 5381 + " clip=" + (intent != null ? intent.getClipData() : null) 5382 + " from " + intent + "; flags=0x" 5383 + Integer.toHexString(intent != null ? intent.getFlags() : 0)); 5384 5385 if (targetPkg == null) { 5386 throw new NullPointerException("targetPkg"); 5387 } 5388 5389 if (intent == null) { 5390 return null; 5391 } 5392 Uri data = intent.getData(); 5393 ClipData clip = intent.getClipData(); 5394 if (data == null && clip == null) { 5395 return null; 5396 } 5397 if (data != null) { 5398 int target = checkGrantUriPermissionLocked(callingUid, targetPkg, data, 5399 mode, needed != null ? needed.targetUid : -1); 5400 if (target > 0) { 5401 if (needed == null) { 5402 needed = new NeededUriGrants(targetPkg, target, mode); 5403 } 5404 needed.add(data); 5405 } 5406 } 5407 if (clip != null) { 5408 for (int i=0; i<clip.getItemCount(); i++) { 5409 Uri uri = clip.getItemAt(i).getUri(); 5410 if (uri != null) { 5411 int target = -1; 5412 target = checkGrantUriPermissionLocked(callingUid, targetPkg, uri, 5413 mode, needed != null ? needed.targetUid : -1); 5414 if (target > 0) { 5415 if (needed == null) { 5416 needed = new NeededUriGrants(targetPkg, target, mode); 5417 } 5418 needed.add(uri); 5419 } 5420 } else { 5421 Intent clipIntent = clip.getItemAt(i).getIntent(); 5422 if (clipIntent != null) { 5423 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked( 5424 callingUid, targetPkg, clipIntent, mode, needed); 5425 if (newNeeded != null) { 5426 needed = newNeeded; 5427 } 5428 } 5429 } 5430 } 5431 } 5432 5433 return needed; 5434 } 5435 5436 /** 5437 * Like grantUriPermissionUncheckedLocked, but takes an Intent. 5438 */ 5439 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed, 5440 UriPermissionOwner owner) { 5441 if (needed != null) { 5442 for (int i=0; i<needed.size(); i++) { 5443 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg, 5444 needed.get(i), needed.flags, owner); 5445 } 5446 } 5447 } 5448 5449 void grantUriPermissionFromIntentLocked(int callingUid, 5450 String targetPkg, Intent intent, UriPermissionOwner owner) { 5451 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, 5452 intent, intent != null ? intent.getFlags() : 0, null); 5453 if (needed == null) { 5454 return; 5455 } 5456 5457 grantUriPermissionUncheckedFromIntentLocked(needed, owner); 5458 } 5459 5460 public void grantUriPermission(IApplicationThread caller, String targetPkg, 5461 Uri uri, int modeFlags) { 5462 enforceNotIsolatedCaller("grantUriPermission"); 5463 synchronized(this) { 5464 final ProcessRecord r = getRecordForAppLocked(caller); 5465 if (r == null) { 5466 throw new SecurityException("Unable to find app for caller " 5467 + caller 5468 + " when granting permission to uri " + uri); 5469 } 5470 if (targetPkg == null) { 5471 throw new IllegalArgumentException("null target"); 5472 } 5473 if (uri == null) { 5474 throw new IllegalArgumentException("null uri"); 5475 } 5476 5477 grantUriPermissionLocked(r.uid, targetPkg, uri, modeFlags, 5478 null); 5479 } 5480 } 5481 5482 void removeUriPermissionIfNeededLocked(UriPermission perm) { 5483 if ((perm.modeFlags&(Intent.FLAG_GRANT_READ_URI_PERMISSION 5484 |Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) == 0) { 5485 HashMap<Uri, UriPermission> perms 5486 = mGrantedUriPermissions.get(perm.uid); 5487 if (perms != null) { 5488 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5489 "Removing " + perm.uid + " permission to " + perm.uri); 5490 perms.remove(perm.uri); 5491 if (perms.size() == 0) { 5492 mGrantedUriPermissions.remove(perm.uid); 5493 } 5494 } 5495 } 5496 } 5497 5498 private void revokeUriPermissionLocked(int callingUid, Uri uri, 5499 int modeFlags) { 5500 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION 5501 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 5502 if (modeFlags == 0) { 5503 return; 5504 } 5505 5506 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5507 "Revoking all granted permissions to " + uri); 5508 5509 final IPackageManager pm = AppGlobals.getPackageManager(); 5510 5511 final String authority = uri.getAuthority(); 5512 ProviderInfo pi = null; 5513 int userId = UserHandle.getUserId(callingUid); 5514 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userId); 5515 if (cpr != null) { 5516 pi = cpr.info; 5517 } else { 5518 try { 5519 pi = pm.resolveContentProvider(authority, 5520 PackageManager.GET_URI_PERMISSION_PATTERNS, userId); 5521 } catch (RemoteException ex) { 5522 } 5523 } 5524 if (pi == null) { 5525 Slog.w(TAG, "No content provider found for permission revoke: " + uri.toSafeString()); 5526 return; 5527 } 5528 5529 // Does the caller have this permission on the URI? 5530 if (!checkHoldingPermissionsLocked(pm, pi, uri, callingUid, modeFlags)) { 5531 // Right now, if you are not the original owner of the permission, 5532 // you are not allowed to revoke it. 5533 //if (!checkUriPermissionLocked(uri, callingUid, modeFlags)) { 5534 throw new SecurityException("Uid " + callingUid 5535 + " does not have permission to uri " + uri); 5536 //} 5537 } 5538 5539 // Go through all of the permissions and remove any that match. 5540 final List<String> SEGMENTS = uri.getPathSegments(); 5541 if (SEGMENTS != null) { 5542 final int NS = SEGMENTS.size(); 5543 int N = mGrantedUriPermissions.size(); 5544 for (int i=0; i<N; i++) { 5545 HashMap<Uri, UriPermission> perms 5546 = mGrantedUriPermissions.valueAt(i); 5547 Iterator<UriPermission> it = perms.values().iterator(); 5548 toploop: 5549 while (it.hasNext()) { 5550 UriPermission perm = it.next(); 5551 Uri targetUri = perm.uri; 5552 if (!authority.equals(targetUri.getAuthority())) { 5553 continue; 5554 } 5555 List<String> targetSegments = targetUri.getPathSegments(); 5556 if (targetSegments == null) { 5557 continue; 5558 } 5559 if (targetSegments.size() < NS) { 5560 continue; 5561 } 5562 for (int j=0; j<NS; j++) { 5563 if (!SEGMENTS.get(j).equals(targetSegments.get(j))) { 5564 continue toploop; 5565 } 5566 } 5567 if (DEBUG_URI_PERMISSION) Slog.v(TAG, 5568 "Revoking " + perm.uid + " permission to " + perm.uri); 5569 perm.clearModes(modeFlags); 5570 if (perm.modeFlags == 0) { 5571 it.remove(); 5572 } 5573 } 5574 if (perms.size() == 0) { 5575 mGrantedUriPermissions.remove( 5576 mGrantedUriPermissions.keyAt(i)); 5577 N--; 5578 i--; 5579 } 5580 } 5581 } 5582 } 5583 5584 public void revokeUriPermission(IApplicationThread caller, Uri uri, 5585 int modeFlags) { 5586 enforceNotIsolatedCaller("revokeUriPermission"); 5587 synchronized(this) { 5588 final ProcessRecord r = getRecordForAppLocked(caller); 5589 if (r == null) { 5590 throw new SecurityException("Unable to find app for caller " 5591 + caller 5592 + " when revoking permission to uri " + uri); 5593 } 5594 if (uri == null) { 5595 Slog.w(TAG, "revokeUriPermission: null uri"); 5596 return; 5597 } 5598 5599 modeFlags &= (Intent.FLAG_GRANT_READ_URI_PERMISSION 5600 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 5601 if (modeFlags == 0) { 5602 return; 5603 } 5604 5605 final IPackageManager pm = AppGlobals.getPackageManager(); 5606 5607 final String authority = uri.getAuthority(); 5608 ProviderInfo pi = null; 5609 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, r.userId); 5610 if (cpr != null) { 5611 pi = cpr.info; 5612 } else { 5613 try { 5614 pi = pm.resolveContentProvider(authority, 5615 PackageManager.GET_URI_PERMISSION_PATTERNS, r.userId); 5616 } catch (RemoteException ex) { 5617 } 5618 } 5619 if (pi == null) { 5620 Slog.w(TAG, "No content provider found for permission revoke: " 5621 + uri.toSafeString()); 5622 return; 5623 } 5624 5625 revokeUriPermissionLocked(r.uid, uri, modeFlags); 5626 } 5627 } 5628 5629 @Override 5630 public IBinder newUriPermissionOwner(String name) { 5631 enforceNotIsolatedCaller("newUriPermissionOwner"); 5632 synchronized(this) { 5633 UriPermissionOwner owner = new UriPermissionOwner(this, name); 5634 return owner.getExternalTokenLocked(); 5635 } 5636 } 5637 5638 @Override 5639 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, 5640 Uri uri, int modeFlags) { 5641 synchronized(this) { 5642 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 5643 if (owner == null) { 5644 throw new IllegalArgumentException("Unknown owner: " + token); 5645 } 5646 if (fromUid != Binder.getCallingUid()) { 5647 if (Binder.getCallingUid() != Process.myUid()) { 5648 // Only system code can grant URI permissions on behalf 5649 // of other users. 5650 throw new SecurityException("nice try"); 5651 } 5652 } 5653 if (targetPkg == null) { 5654 throw new IllegalArgumentException("null target"); 5655 } 5656 if (uri == null) { 5657 throw new IllegalArgumentException("null uri"); 5658 } 5659 5660 grantUriPermissionLocked(fromUid, targetPkg, uri, modeFlags, owner); 5661 } 5662 } 5663 5664 @Override 5665 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode) { 5666 synchronized(this) { 5667 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 5668 if (owner == null) { 5669 throw new IllegalArgumentException("Unknown owner: " + token); 5670 } 5671 5672 if (uri == null) { 5673 owner.removeUriPermissionsLocked(mode); 5674 } else { 5675 owner.removeUriPermissionLocked(uri, mode); 5676 } 5677 } 5678 } 5679 5680 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 5681 synchronized (this) { 5682 ProcessRecord app = 5683 who != null ? getRecordForAppLocked(who) : null; 5684 if (app == null) return; 5685 5686 Message msg = Message.obtain(); 5687 msg.what = WAIT_FOR_DEBUGGER_MSG; 5688 msg.obj = app; 5689 msg.arg1 = waiting ? 1 : 0; 5690 mHandler.sendMessage(msg); 5691 } 5692 } 5693 5694 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 5695 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ); 5696 final long hiddenAppMem = mProcessList.getMemLevel(ProcessList.HIDDEN_APP_MIN_ADJ); 5697 outInfo.availMem = Process.getFreeMemory(); 5698 outInfo.totalMem = Process.getTotalMemory(); 5699 outInfo.threshold = homeAppMem; 5700 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((hiddenAppMem-homeAppMem)/2)); 5701 outInfo.hiddenAppThreshold = hiddenAppMem; 5702 outInfo.secondaryServerThreshold = mProcessList.getMemLevel( 5703 ProcessList.SERVICE_ADJ); 5704 outInfo.visibleAppThreshold = mProcessList.getMemLevel( 5705 ProcessList.VISIBLE_APP_ADJ); 5706 outInfo.foregroundAppThreshold = mProcessList.getMemLevel( 5707 ProcessList.FOREGROUND_APP_ADJ); 5708 } 5709 5710 // ========================================================= 5711 // TASK MANAGEMENT 5712 // ========================================================= 5713 5714 public List getTasks(int maxNum, int flags, 5715 IThumbnailReceiver receiver) { 5716 ArrayList list = new ArrayList(); 5717 5718 PendingThumbnailsRecord pending = null; 5719 IApplicationThread topThumbnail = null; 5720 ActivityRecord topRecord = null; 5721 5722 synchronized(this) { 5723 if (localLOGV) Slog.v( 5724 TAG, "getTasks: max=" + maxNum + ", flags=" + flags 5725 + ", receiver=" + receiver); 5726 5727 if (checkCallingPermission(android.Manifest.permission.GET_TASKS) 5728 != PackageManager.PERMISSION_GRANTED) { 5729 if (receiver != null) { 5730 // If the caller wants to wait for pending thumbnails, 5731 // it ain't gonna get them. 5732 try { 5733 receiver.finished(); 5734 } catch (RemoteException ex) { 5735 } 5736 } 5737 String msg = "Permission Denial: getTasks() from pid=" 5738 + Binder.getCallingPid() 5739 + ", uid=" + Binder.getCallingUid() 5740 + " requires " + android.Manifest.permission.GET_TASKS; 5741 Slog.w(TAG, msg); 5742 throw new SecurityException(msg); 5743 } 5744 5745 int pos = mMainStack.mHistory.size()-1; 5746 ActivityRecord next = 5747 pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null; 5748 ActivityRecord top = null; 5749 TaskRecord curTask = null; 5750 int numActivities = 0; 5751 int numRunning = 0; 5752 while (pos >= 0 && maxNum > 0) { 5753 final ActivityRecord r = next; 5754 pos--; 5755 next = pos >= 0 ? (ActivityRecord)mMainStack.mHistory.get(pos) : null; 5756 5757 // Initialize state for next task if needed. 5758 if (top == null || 5759 (top.state == ActivityState.INITIALIZING 5760 && top.task == r.task)) { 5761 top = r; 5762 curTask = r.task; 5763 numActivities = numRunning = 0; 5764 } 5765 5766 // Add 'r' into the current task. 5767 numActivities++; 5768 if (r.app != null && r.app.thread != null) { 5769 numRunning++; 5770 } 5771 5772 if (localLOGV) Slog.v( 5773 TAG, r.intent.getComponent().flattenToShortString() 5774 + ": task=" + r.task); 5775 5776 // If the next one is a different task, generate a new 5777 // TaskInfo entry for what we have. 5778 if (next == null || next.task != curTask) { 5779 ActivityManager.RunningTaskInfo ci 5780 = new ActivityManager.RunningTaskInfo(); 5781 ci.id = curTask.taskId; 5782 ci.baseActivity = r.intent.getComponent(); 5783 ci.topActivity = top.intent.getComponent(); 5784 if (top.thumbHolder != null) { 5785 ci.description = top.thumbHolder.lastDescription; 5786 } 5787 ci.numActivities = numActivities; 5788 ci.numRunning = numRunning; 5789 //System.out.println( 5790 // "#" + maxNum + ": " + " descr=" + ci.description); 5791 if (ci.thumbnail == null && receiver != null) { 5792 if (localLOGV) Slog.v( 5793 TAG, "State=" + top.state + "Idle=" + top.idle 5794 + " app=" + top.app 5795 + " thr=" + (top.app != null ? top.app.thread : null)); 5796 if (top.state == ActivityState.RESUMED 5797 || top.state == ActivityState.PAUSING) { 5798 if (top.idle && top.app != null 5799 && top.app.thread != null) { 5800 topRecord = top; 5801 topThumbnail = top.app.thread; 5802 } else { 5803 top.thumbnailNeeded = true; 5804 } 5805 } 5806 if (pending == null) { 5807 pending = new PendingThumbnailsRecord(receiver); 5808 } 5809 pending.pendingRecords.add(top); 5810 } 5811 list.add(ci); 5812 maxNum--; 5813 top = null; 5814 } 5815 } 5816 5817 if (pending != null) { 5818 mPendingThumbnails.add(pending); 5819 } 5820 } 5821 5822 if (localLOGV) Slog.v(TAG, "We have pending thumbnails: " + pending); 5823 5824 if (topThumbnail != null) { 5825 if (localLOGV) Slog.v(TAG, "Requesting top thumbnail"); 5826 try { 5827 topThumbnail.requestThumbnail(topRecord.appToken); 5828 } catch (Exception e) { 5829 Slog.w(TAG, "Exception thrown when requesting thumbnail", e); 5830 sendPendingThumbnail(null, topRecord.appToken, null, null, true); 5831 } 5832 } 5833 5834 if (pending == null && receiver != null) { 5835 // In this case all thumbnails were available and the client 5836 // is being asked to be told when the remaining ones come in... 5837 // which is unusually, since the top-most currently running 5838 // activity should never have a canned thumbnail! Oh well. 5839 try { 5840 receiver.finished(); 5841 } catch (RemoteException ex) { 5842 } 5843 } 5844 5845 return list; 5846 } 5847 5848 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, 5849 int flags, int userId) { 5850 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 5851 false, true, "getRecentTasks", null); 5852 5853 synchronized (this) { 5854 enforceCallingPermission(android.Manifest.permission.GET_TASKS, 5855 "getRecentTasks()"); 5856 final boolean detailed = checkCallingPermission( 5857 android.Manifest.permission.GET_DETAILED_TASKS) 5858 == PackageManager.PERMISSION_GRANTED; 5859 5860 IPackageManager pm = AppGlobals.getPackageManager(); 5861 5862 final int N = mRecentTasks.size(); 5863 ArrayList<ActivityManager.RecentTaskInfo> res 5864 = new ArrayList<ActivityManager.RecentTaskInfo>( 5865 maxNum < N ? maxNum : N); 5866 for (int i=0; i<N && maxNum > 0; i++) { 5867 TaskRecord tr = mRecentTasks.get(i); 5868 // Only add calling user's recent tasks 5869 if (tr.userId != userId) continue; 5870 // Return the entry if desired by the caller. We always return 5871 // the first entry, because callers always expect this to be the 5872 // foreground app. We may filter others if the caller has 5873 // not supplied RECENT_WITH_EXCLUDED and there is some reason 5874 // we should exclude the entry. 5875 5876 if (i == 0 5877 || ((flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0) 5878 || (tr.intent == null) 5879 || ((tr.intent.getFlags() 5880 &Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0)) { 5881 ActivityManager.RecentTaskInfo rti 5882 = new ActivityManager.RecentTaskInfo(); 5883 rti.id = tr.numActivities > 0 ? tr.taskId : -1; 5884 rti.persistentId = tr.taskId; 5885 rti.baseIntent = new Intent( 5886 tr.intent != null ? tr.intent : tr.affinityIntent); 5887 if (!detailed) { 5888 rti.baseIntent.replaceExtras((Bundle)null); 5889 } 5890 rti.origActivity = tr.origActivity; 5891 rti.description = tr.lastDescription; 5892 5893 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0) { 5894 // Check whether this activity is currently available. 5895 try { 5896 if (rti.origActivity != null) { 5897 if (pm.getActivityInfo(rti.origActivity, 0, userId) 5898 == null) { 5899 continue; 5900 } 5901 } else if (rti.baseIntent != null) { 5902 if (pm.queryIntentActivities(rti.baseIntent, 5903 null, 0, userId) == null) { 5904 continue; 5905 } 5906 } 5907 } catch (RemoteException e) { 5908 // Will never happen. 5909 } 5910 } 5911 5912 res.add(rti); 5913 maxNum--; 5914 } 5915 } 5916 return res; 5917 } 5918 } 5919 5920 private TaskRecord taskForIdLocked(int id) { 5921 final int N = mRecentTasks.size(); 5922 for (int i=0; i<N; i++) { 5923 TaskRecord tr = mRecentTasks.get(i); 5924 if (tr.taskId == id) { 5925 return tr; 5926 } 5927 } 5928 return null; 5929 } 5930 5931 public ActivityManager.TaskThumbnails getTaskThumbnails(int id) { 5932 synchronized (this) { 5933 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER, 5934 "getTaskThumbnails()"); 5935 TaskRecord tr = taskForIdLocked(id); 5936 if (tr != null) { 5937 return mMainStack.getTaskThumbnailsLocked(tr); 5938 } 5939 } 5940 return null; 5941 } 5942 5943 public Bitmap getTaskTopThumbnail(int id) { 5944 synchronized (this) { 5945 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER, 5946 "getTaskTopThumbnail()"); 5947 TaskRecord tr = taskForIdLocked(id); 5948 if (tr != null) { 5949 return mMainStack.getTaskTopThumbnailLocked(tr); 5950 } 5951 } 5952 return null; 5953 } 5954 5955 public boolean removeSubTask(int taskId, int subTaskIndex) { 5956 synchronized (this) { 5957 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, 5958 "removeSubTask()"); 5959 long ident = Binder.clearCallingIdentity(); 5960 try { 5961 return mMainStack.removeTaskActivitiesLocked(taskId, subTaskIndex, 5962 true) != null; 5963 } finally { 5964 Binder.restoreCallingIdentity(ident); 5965 } 5966 } 5967 } 5968 5969 private void cleanUpRemovedTaskLocked(TaskRecord tr, int flags) { 5970 final boolean killProcesses = (flags&ActivityManager.REMOVE_TASK_KILL_PROCESS) != 0; 5971 Intent baseIntent = new Intent( 5972 tr.intent != null ? tr.intent : tr.affinityIntent); 5973 ComponentName component = baseIntent.getComponent(); 5974 if (component == null) { 5975 Slog.w(TAG, "Now component for base intent of task: " + tr); 5976 return; 5977 } 5978 5979 // Find any running services associated with this app. 5980 mServices.cleanUpRemovedTaskLocked(tr, component, baseIntent); 5981 5982 if (killProcesses) { 5983 // Find any running processes associated with this app. 5984 final String pkg = component.getPackageName(); 5985 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 5986 HashMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap(); 5987 for (SparseArray<ProcessRecord> uids : pmap.values()) { 5988 for (int i=0; i<uids.size(); i++) { 5989 ProcessRecord proc = uids.valueAt(i); 5990 if (proc.userId != tr.userId) { 5991 continue; 5992 } 5993 if (!proc.pkgList.contains(pkg)) { 5994 continue; 5995 } 5996 procs.add(proc); 5997 } 5998 } 5999 6000 // Kill the running processes. 6001 for (int i=0; i<procs.size(); i++) { 6002 ProcessRecord pr = procs.get(i); 6003 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) { 6004 Slog.i(TAG, "Killing " + pr.toShortString() + ": remove task"); 6005 EventLog.writeEvent(EventLogTags.AM_KILL, pr.userId, pr.pid, 6006 pr.processName, pr.setAdj, "remove task"); 6007 pr.killedBackground = true; 6008 Process.killProcessQuiet(pr.pid); 6009 } else { 6010 pr.waitingToKill = "remove task"; 6011 } 6012 } 6013 } 6014 } 6015 6016 public boolean removeTask(int taskId, int flags) { 6017 synchronized (this) { 6018 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, 6019 "removeTask()"); 6020 long ident = Binder.clearCallingIdentity(); 6021 try { 6022 ActivityRecord r = mMainStack.removeTaskActivitiesLocked(taskId, -1, 6023 false); 6024 if (r != null) { 6025 mRecentTasks.remove(r.task); 6026 cleanUpRemovedTaskLocked(r.task, flags); 6027 return true; 6028 } else { 6029 TaskRecord tr = null; 6030 int i=0; 6031 while (i < mRecentTasks.size()) { 6032 TaskRecord t = mRecentTasks.get(i); 6033 if (t.taskId == taskId) { 6034 tr = t; 6035 break; 6036 } 6037 i++; 6038 } 6039 if (tr != null) { 6040 if (tr.numActivities <= 0) { 6041 // Caller is just removing a recent task that is 6042 // not actively running. That is easy! 6043 mRecentTasks.remove(i); 6044 cleanUpRemovedTaskLocked(tr, flags); 6045 return true; 6046 } else { 6047 Slog.w(TAG, "removeTask: task " + taskId 6048 + " does not have activities to remove, " 6049 + " but numActivities=" + tr.numActivities 6050 + ": " + tr); 6051 } 6052 } 6053 } 6054 } finally { 6055 Binder.restoreCallingIdentity(ident); 6056 } 6057 } 6058 return false; 6059 } 6060 6061 private final int findAffinityTaskTopLocked(int startIndex, String affinity) { 6062 int j; 6063 TaskRecord startTask = ((ActivityRecord)mMainStack.mHistory.get(startIndex)).task; 6064 TaskRecord jt = startTask; 6065 6066 // First look backwards 6067 for (j=startIndex-1; j>=0; j--) { 6068 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j); 6069 if (r.task != jt) { 6070 jt = r.task; 6071 if (affinity.equals(jt.affinity)) { 6072 return j; 6073 } 6074 } 6075 } 6076 6077 // Now look forwards 6078 final int N = mMainStack.mHistory.size(); 6079 jt = startTask; 6080 for (j=startIndex+1; j<N; j++) { 6081 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(j); 6082 if (r.task != jt) { 6083 if (affinity.equals(jt.affinity)) { 6084 return j; 6085 } 6086 jt = r.task; 6087 } 6088 } 6089 6090 // Might it be at the top? 6091 if (affinity.equals(((ActivityRecord)mMainStack.mHistory.get(N-1)).task.affinity)) { 6092 return N-1; 6093 } 6094 6095 return -1; 6096 } 6097 6098 /** 6099 * TODO: Add mController hook 6100 */ 6101 public void moveTaskToFront(int task, int flags, Bundle options) { 6102 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 6103 "moveTaskToFront()"); 6104 6105 synchronized(this) { 6106 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 6107 Binder.getCallingUid(), "Task to front")) { 6108 ActivityOptions.abort(options); 6109 return; 6110 } 6111 final long origId = Binder.clearCallingIdentity(); 6112 try { 6113 TaskRecord tr = taskForIdLocked(task); 6114 if (tr != null) { 6115 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) { 6116 mMainStack.mUserLeaving = true; 6117 } 6118 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) { 6119 // Caller wants the home activity moved with it. To accomplish this, 6120 // we'll just move the home task to the top first. 6121 mMainStack.moveHomeToFrontLocked(); 6122 } 6123 mMainStack.moveTaskToFrontLocked(tr, null, options); 6124 return; 6125 } 6126 for (int i=mMainStack.mHistory.size()-1; i>=0; i--) { 6127 ActivityRecord hr = (ActivityRecord)mMainStack.mHistory.get(i); 6128 if (hr.task.taskId == task) { 6129 if ((flags&ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) { 6130 mMainStack.mUserLeaving = true; 6131 } 6132 if ((flags&ActivityManager.MOVE_TASK_WITH_HOME) != 0) { 6133 // Caller wants the home activity moved with it. To accomplish this, 6134 // we'll just move the home task to the top first. 6135 mMainStack.moveHomeToFrontLocked(); 6136 } 6137 mMainStack.moveTaskToFrontLocked(hr.task, null, options); 6138 return; 6139 } 6140 } 6141 } finally { 6142 Binder.restoreCallingIdentity(origId); 6143 } 6144 ActivityOptions.abort(options); 6145 } 6146 } 6147 6148 public void moveTaskToBack(int task) { 6149 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 6150 "moveTaskToBack()"); 6151 6152 synchronized(this) { 6153 if (mMainStack.mResumedActivity != null 6154 && mMainStack.mResumedActivity.task.taskId == task) { 6155 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 6156 Binder.getCallingUid(), "Task to back")) { 6157 return; 6158 } 6159 } 6160 final long origId = Binder.clearCallingIdentity(); 6161 mMainStack.moveTaskToBackLocked(task, null); 6162 Binder.restoreCallingIdentity(origId); 6163 } 6164 } 6165 6166 /** 6167 * Moves an activity, and all of the other activities within the same task, to the bottom 6168 * of the history stack. The activity's order within the task is unchanged. 6169 * 6170 * @param token A reference to the activity we wish to move 6171 * @param nonRoot If false then this only works if the activity is the root 6172 * of a task; if true it will work for any activity in a task. 6173 * @return Returns true if the move completed, false if not. 6174 */ 6175 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 6176 enforceNotIsolatedCaller("moveActivityTaskToBack"); 6177 synchronized(this) { 6178 final long origId = Binder.clearCallingIdentity(); 6179 int taskId = getTaskForActivityLocked(token, !nonRoot); 6180 if (taskId >= 0) { 6181 return mMainStack.moveTaskToBackLocked(taskId, null); 6182 } 6183 Binder.restoreCallingIdentity(origId); 6184 } 6185 return false; 6186 } 6187 6188 public void moveTaskBackwards(int task) { 6189 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 6190 "moveTaskBackwards()"); 6191 6192 synchronized(this) { 6193 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 6194 Binder.getCallingUid(), "Task backwards")) { 6195 return; 6196 } 6197 final long origId = Binder.clearCallingIdentity(); 6198 moveTaskBackwardsLocked(task); 6199 Binder.restoreCallingIdentity(origId); 6200 } 6201 } 6202 6203 private final void moveTaskBackwardsLocked(int task) { 6204 Slog.e(TAG, "moveTaskBackwards not yet implemented!"); 6205 } 6206 6207 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 6208 synchronized(this) { 6209 return getTaskForActivityLocked(token, onlyRoot); 6210 } 6211 } 6212 6213 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) { 6214 final int N = mMainStack.mHistory.size(); 6215 TaskRecord lastTask = null; 6216 for (int i=0; i<N; i++) { 6217 ActivityRecord r = (ActivityRecord)mMainStack.mHistory.get(i); 6218 if (r.appToken == token) { 6219 if (!onlyRoot || lastTask != r.task) { 6220 return r.task.taskId; 6221 } 6222 return -1; 6223 } 6224 lastTask = r.task; 6225 } 6226 6227 return -1; 6228 } 6229 6230 // ========================================================= 6231 // THUMBNAILS 6232 // ========================================================= 6233 6234 public void reportThumbnail(IBinder token, 6235 Bitmap thumbnail, CharSequence description) { 6236 //System.out.println("Report thumbnail for " + token + ": " + thumbnail); 6237 final long origId = Binder.clearCallingIdentity(); 6238 sendPendingThumbnail(null, token, thumbnail, description, true); 6239 Binder.restoreCallingIdentity(origId); 6240 } 6241 6242 final void sendPendingThumbnail(ActivityRecord r, IBinder token, 6243 Bitmap thumbnail, CharSequence description, boolean always) { 6244 TaskRecord task = null; 6245 ArrayList receivers = null; 6246 6247 //System.out.println("Send pending thumbnail: " + r); 6248 6249 synchronized(this) { 6250 if (r == null) { 6251 r = mMainStack.isInStackLocked(token); 6252 if (r == null) { 6253 return; 6254 } 6255 } 6256 if (thumbnail == null && r.thumbHolder != null) { 6257 thumbnail = r.thumbHolder.lastThumbnail; 6258 description = r.thumbHolder.lastDescription; 6259 } 6260 if (thumbnail == null && !always) { 6261 // If there is no thumbnail, and this entry is not actually 6262 // going away, then abort for now and pick up the next 6263 // thumbnail we get. 6264 return; 6265 } 6266 task = r.task; 6267 6268 int N = mPendingThumbnails.size(); 6269 int i=0; 6270 while (i<N) { 6271 PendingThumbnailsRecord pr = 6272 (PendingThumbnailsRecord)mPendingThumbnails.get(i); 6273 //System.out.println("Looking in " + pr.pendingRecords); 6274 if (pr.pendingRecords.remove(r)) { 6275 if (receivers == null) { 6276 receivers = new ArrayList(); 6277 } 6278 receivers.add(pr); 6279 if (pr.pendingRecords.size() == 0) { 6280 pr.finished = true; 6281 mPendingThumbnails.remove(i); 6282 N--; 6283 continue; 6284 } 6285 } 6286 i++; 6287 } 6288 } 6289 6290 if (receivers != null) { 6291 final int N = receivers.size(); 6292 for (int i=0; i<N; i++) { 6293 try { 6294 PendingThumbnailsRecord pr = 6295 (PendingThumbnailsRecord)receivers.get(i); 6296 pr.receiver.newThumbnail( 6297 task != null ? task.taskId : -1, thumbnail, description); 6298 if (pr.finished) { 6299 pr.receiver.finished(); 6300 } 6301 } catch (Exception e) { 6302 Slog.w(TAG, "Exception thrown when sending thumbnail", e); 6303 } 6304 } 6305 } 6306 } 6307 6308 // ========================================================= 6309 // CONTENT PROVIDERS 6310 // ========================================================= 6311 6312 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) { 6313 List<ProviderInfo> providers = null; 6314 try { 6315 providers = AppGlobals.getPackageManager(). 6316 queryContentProviders(app.processName, app.uid, 6317 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS); 6318 } catch (RemoteException ex) { 6319 } 6320 if (DEBUG_MU) 6321 Slog.v(TAG_MU, "generateApplicationProvidersLocked, app.info.uid = " + app.uid); 6322 int userId = app.userId; 6323 if (providers != null) { 6324 int N = providers.size(); 6325 for (int i=0; i<N; i++) { 6326 ProviderInfo cpi = 6327 (ProviderInfo)providers.get(i); 6328 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 6329 cpi.name, cpi.flags); 6330 if (singleton && UserHandle.getUserId(app.uid) != 0) { 6331 // This is a singleton provider, but a user besides the 6332 // default user is asking to initialize a process it runs 6333 // in... well, no, it doesn't actually run in this process, 6334 // it runs in the process of the default user. Get rid of it. 6335 providers.remove(i); 6336 N--; 6337 continue; 6338 } 6339 6340 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 6341 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId); 6342 if (cpr == null) { 6343 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton); 6344 mProviderMap.putProviderByClass(comp, cpr); 6345 } 6346 if (DEBUG_MU) 6347 Slog.v(TAG_MU, "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid); 6348 app.pubProviders.put(cpi.name, cpr); 6349 app.addPackage(cpi.applicationInfo.packageName); 6350 ensurePackageDexOpt(cpi.applicationInfo.packageName); 6351 } 6352 } 6353 return providers; 6354 } 6355 6356 /** 6357 * Check if {@link ProcessRecord} has a possible chance at accessing the 6358 * given {@link ProviderInfo}. Final permission checking is always done 6359 * in {@link ContentProvider}. 6360 */ 6361 private final String checkContentProviderPermissionLocked( 6362 ProviderInfo cpi, ProcessRecord r) { 6363 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid(); 6364 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid(); 6365 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid, 6366 cpi.applicationInfo.uid, cpi.exported) 6367 == PackageManager.PERMISSION_GRANTED) { 6368 return null; 6369 } 6370 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid, 6371 cpi.applicationInfo.uid, cpi.exported) 6372 == PackageManager.PERMISSION_GRANTED) { 6373 return null; 6374 } 6375 6376 PathPermission[] pps = cpi.pathPermissions; 6377 if (pps != null) { 6378 int i = pps.length; 6379 while (i > 0) { 6380 i--; 6381 PathPermission pp = pps[i]; 6382 if (checkComponentPermission(pp.getReadPermission(), callingPid, callingUid, 6383 cpi.applicationInfo.uid, cpi.exported) 6384 == PackageManager.PERMISSION_GRANTED) { 6385 return null; 6386 } 6387 if (checkComponentPermission(pp.getWritePermission(), callingPid, callingUid, 6388 cpi.applicationInfo.uid, cpi.exported) 6389 == PackageManager.PERMISSION_GRANTED) { 6390 return null; 6391 } 6392 } 6393 } 6394 6395 HashMap<Uri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 6396 if (perms != null) { 6397 for (Map.Entry<Uri, UriPermission> uri : perms.entrySet()) { 6398 if (uri.getKey().getAuthority().equals(cpi.authority)) { 6399 return null; 6400 } 6401 } 6402 } 6403 6404 String msg; 6405 if (!cpi.exported) { 6406 msg = "Permission Denial: opening provider " + cpi.name 6407 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 6408 + ", uid=" + callingUid + ") that is not exported from uid " 6409 + cpi.applicationInfo.uid; 6410 } else { 6411 msg = "Permission Denial: opening provider " + cpi.name 6412 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 6413 + ", uid=" + callingUid + ") requires " 6414 + cpi.readPermission + " or " + cpi.writePermission; 6415 } 6416 Slog.w(TAG, msg); 6417 return msg; 6418 } 6419 6420 ContentProviderConnection incProviderCountLocked(ProcessRecord r, 6421 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 6422 if (r != null) { 6423 for (int i=0; i<r.conProviders.size(); i++) { 6424 ContentProviderConnection conn = r.conProviders.get(i); 6425 if (conn.provider == cpr) { 6426 if (DEBUG_PROVIDER) Slog.v(TAG, 6427 "Adding provider requested by " 6428 + r.processName + " from process " 6429 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 6430 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 6431 if (stable) { 6432 conn.stableCount++; 6433 conn.numStableIncs++; 6434 } else { 6435 conn.unstableCount++; 6436 conn.numUnstableIncs++; 6437 } 6438 return conn; 6439 } 6440 } 6441 ContentProviderConnection conn = new ContentProviderConnection(cpr, r); 6442 if (stable) { 6443 conn.stableCount = 1; 6444 conn.numStableIncs = 1; 6445 } else { 6446 conn.unstableCount = 1; 6447 conn.numUnstableIncs = 1; 6448 } 6449 cpr.connections.add(conn); 6450 r.conProviders.add(conn); 6451 return conn; 6452 } 6453 cpr.addExternalProcessHandleLocked(externalProcessToken); 6454 return null; 6455 } 6456 6457 boolean decProviderCountLocked(ContentProviderConnection conn, 6458 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 6459 if (conn != null) { 6460 cpr = conn.provider; 6461 if (DEBUG_PROVIDER) Slog.v(TAG, 6462 "Removing provider requested by " 6463 + conn.client.processName + " from process " 6464 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 6465 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 6466 if (stable) { 6467 conn.stableCount--; 6468 } else { 6469 conn.unstableCount--; 6470 } 6471 if (conn.stableCount == 0 && conn.unstableCount == 0) { 6472 cpr.connections.remove(conn); 6473 conn.client.conProviders.remove(conn); 6474 return true; 6475 } 6476 return false; 6477 } 6478 cpr.removeExternalProcessHandleLocked(externalProcessToken); 6479 return false; 6480 } 6481 6482 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller, 6483 String name, IBinder token, boolean stable, int userId) { 6484 ContentProviderRecord cpr; 6485 ContentProviderConnection conn = null; 6486 ProviderInfo cpi = null; 6487 6488 synchronized(this) { 6489 ProcessRecord r = null; 6490 if (caller != null) { 6491 r = getRecordForAppLocked(caller); 6492 if (r == null) { 6493 throw new SecurityException( 6494 "Unable to find app for caller " + caller 6495 + " (pid=" + Binder.getCallingPid() 6496 + ") when getting content provider " + name); 6497 } 6498 } 6499 6500 // First check if this content provider has been published... 6501 cpr = mProviderMap.getProviderByName(name, userId); 6502 boolean providerRunning = cpr != null; 6503 if (providerRunning) { 6504 cpi = cpr.info; 6505 String msg; 6506 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) { 6507 throw new SecurityException(msg); 6508 } 6509 6510 if (r != null && cpr.canRunHere(r)) { 6511 // This provider has been published or is in the process 6512 // of being published... but it is also allowed to run 6513 // in the caller's process, so don't make a connection 6514 // and just let the caller instantiate its own instance. 6515 ContentProviderHolder holder = cpr.newHolder(null); 6516 // don't give caller the provider object, it needs 6517 // to make its own. 6518 holder.provider = null; 6519 return holder; 6520 } 6521 6522 final long origId = Binder.clearCallingIdentity(); 6523 6524 // In this case the provider instance already exists, so we can 6525 // return it right away. 6526 conn = incProviderCountLocked(r, cpr, token, stable); 6527 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) { 6528 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 6529 // If this is a perceptible app accessing the provider, 6530 // make sure to count it as being accessed and thus 6531 // back up on the LRU list. This is good because 6532 // content providers are often expensive to start. 6533 updateLruProcessLocked(cpr.proc, false); 6534 } 6535 } 6536 6537 if (cpr.proc != null) { 6538 if (false) { 6539 if (cpr.name.flattenToShortString().equals( 6540 "com.android.providers.calendar/.CalendarProvider2")) { 6541 Slog.v(TAG, "****************** KILLING " 6542 + cpr.name.flattenToShortString()); 6543 Process.killProcess(cpr.proc.pid); 6544 } 6545 } 6546 boolean success = updateOomAdjLocked(cpr.proc); 6547 if (DEBUG_PROVIDER) Slog.i(TAG, "Adjust success: " + success); 6548 // NOTE: there is still a race here where a signal could be 6549 // pending on the process even though we managed to update its 6550 // adj level. Not sure what to do about this, but at least 6551 // the race is now smaller. 6552 if (!success) { 6553 // Uh oh... it looks like the provider's process 6554 // has been killed on us. We need to wait for a new 6555 // process to be started, and make sure its death 6556 // doesn't kill our process. 6557 Slog.i(TAG, 6558 "Existing provider " + cpr.name.flattenToShortString() 6559 + " is crashing; detaching " + r); 6560 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable); 6561 appDiedLocked(cpr.proc, cpr.proc.pid, cpr.proc.thread); 6562 if (!lastRef) { 6563 // This wasn't the last ref our process had on 6564 // the provider... we have now been killed, bail. 6565 return null; 6566 } 6567 providerRunning = false; 6568 conn = null; 6569 } 6570 } 6571 6572 Binder.restoreCallingIdentity(origId); 6573 } 6574 6575 boolean singleton; 6576 if (!providerRunning) { 6577 try { 6578 cpi = AppGlobals.getPackageManager(). 6579 resolveContentProvider(name, 6580 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId); 6581 } catch (RemoteException ex) { 6582 } 6583 if (cpi == null) { 6584 return null; 6585 } 6586 singleton = isSingleton(cpi.processName, cpi.applicationInfo, 6587 cpi.name, cpi.flags); 6588 if (singleton) { 6589 userId = 0; 6590 } 6591 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId); 6592 6593 String msg; 6594 if ((msg=checkContentProviderPermissionLocked(cpi, r)) != null) { 6595 throw new SecurityException(msg); 6596 } 6597 6598 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate 6599 && !cpi.processName.equals("system")) { 6600 // If this content provider does not run in the system 6601 // process, and the system is not yet ready to run other 6602 // processes, then fail fast instead of hanging. 6603 throw new IllegalArgumentException( 6604 "Attempt to launch content provider before system ready"); 6605 } 6606 6607 // Make sure that the user who owns this provider is started. If not, 6608 // we don't want to allow it to run. 6609 if (mStartedUsers.get(userId) == null) { 6610 Slog.w(TAG, "Unable to launch app " 6611 + cpi.applicationInfo.packageName + "/" 6612 + cpi.applicationInfo.uid + " for provider " 6613 + name + ": user " + userId + " is stopped"); 6614 return null; 6615 } 6616 6617 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 6618 cpr = mProviderMap.getProviderByClass(comp, userId); 6619 final boolean firstClass = cpr == null; 6620 if (firstClass) { 6621 try { 6622 ApplicationInfo ai = 6623 AppGlobals.getPackageManager(). 6624 getApplicationInfo( 6625 cpi.applicationInfo.packageName, 6626 STOCK_PM_FLAGS, userId); 6627 if (ai == null) { 6628 Slog.w(TAG, "No package info for content provider " 6629 + cpi.name); 6630 return null; 6631 } 6632 ai = getAppInfoForUser(ai, userId); 6633 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton); 6634 } catch (RemoteException ex) { 6635 // pm is in same process, this will never happen. 6636 } 6637 } 6638 6639 if (r != null && cpr.canRunHere(r)) { 6640 // If this is a multiprocess provider, then just return its 6641 // info and allow the caller to instantiate it. Only do 6642 // this if the provider is the same user as the caller's 6643 // process, or can run as root (so can be in any process). 6644 return cpr.newHolder(null); 6645 } 6646 6647 if (DEBUG_PROVIDER) { 6648 RuntimeException e = new RuntimeException("here"); 6649 Slog.w(TAG, "LAUNCHING REMOTE PROVIDER (myuid " + r.uid 6650 + " pruid " + cpr.appInfo.uid + "): " + cpr.info.name, e); 6651 } 6652 6653 // This is single process, and our app is now connecting to it. 6654 // See if we are already in the process of launching this 6655 // provider. 6656 final int N = mLaunchingProviders.size(); 6657 int i; 6658 for (i=0; i<N; i++) { 6659 if (mLaunchingProviders.get(i) == cpr) { 6660 break; 6661 } 6662 } 6663 6664 // If the provider is not already being launched, then get it 6665 // started. 6666 if (i >= N) { 6667 final long origId = Binder.clearCallingIdentity(); 6668 6669 try { 6670 // Content provider is now in use, its package can't be stopped. 6671 try { 6672 AppGlobals.getPackageManager().setPackageStoppedState( 6673 cpr.appInfo.packageName, false, userId); 6674 } catch (RemoteException e) { 6675 } catch (IllegalArgumentException e) { 6676 Slog.w(TAG, "Failed trying to unstop package " 6677 + cpr.appInfo.packageName + ": " + e); 6678 } 6679 6680 ProcessRecord proc = startProcessLocked(cpi.processName, 6681 cpr.appInfo, false, 0, "content provider", 6682 new ComponentName(cpi.applicationInfo.packageName, 6683 cpi.name), false, false); 6684 if (proc == null) { 6685 Slog.w(TAG, "Unable to launch app " 6686 + cpi.applicationInfo.packageName + "/" 6687 + cpi.applicationInfo.uid + " for provider " 6688 + name + ": process is bad"); 6689 return null; 6690 } 6691 cpr.launchingApp = proc; 6692 mLaunchingProviders.add(cpr); 6693 } finally { 6694 Binder.restoreCallingIdentity(origId); 6695 } 6696 } 6697 6698 // Make sure the provider is published (the same provider class 6699 // may be published under multiple names). 6700 if (firstClass) { 6701 mProviderMap.putProviderByClass(comp, cpr); 6702 } 6703 6704 mProviderMap.putProviderByName(name, cpr); 6705 conn = incProviderCountLocked(r, cpr, token, stable); 6706 if (conn != null) { 6707 conn.waiting = true; 6708 } 6709 } 6710 } 6711 6712 // Wait for the provider to be published... 6713 synchronized (cpr) { 6714 while (cpr.provider == null) { 6715 if (cpr.launchingApp == null) { 6716 Slog.w(TAG, "Unable to launch app " 6717 + cpi.applicationInfo.packageName + "/" 6718 + cpi.applicationInfo.uid + " for provider " 6719 + name + ": launching app became null"); 6720 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS, 6721 UserHandle.getUserId(cpi.applicationInfo.uid), 6722 cpi.applicationInfo.packageName, 6723 cpi.applicationInfo.uid, name); 6724 return null; 6725 } 6726 try { 6727 if (DEBUG_MU) { 6728 Slog.v(TAG_MU, "Waiting to start provider " + cpr + " launchingApp=" 6729 + cpr.launchingApp); 6730 } 6731 if (conn != null) { 6732 conn.waiting = true; 6733 } 6734 cpr.wait(); 6735 } catch (InterruptedException ex) { 6736 } finally { 6737 if (conn != null) { 6738 conn.waiting = false; 6739 } 6740 } 6741 } 6742 } 6743 return cpr != null ? cpr.newHolder(conn) : null; 6744 } 6745 6746 public final ContentProviderHolder getContentProvider( 6747 IApplicationThread caller, String name, int userId, boolean stable) { 6748 enforceNotIsolatedCaller("getContentProvider"); 6749 if (caller == null) { 6750 String msg = "null IApplicationThread when getting content provider " 6751 + name; 6752 Slog.w(TAG, msg); 6753 throw new SecurityException(msg); 6754 } 6755 6756 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 6757 false, true, "getContentProvider", null); 6758 return getContentProviderImpl(caller, name, null, stable, userId); 6759 } 6760 6761 public ContentProviderHolder getContentProviderExternal( 6762 String name, int userId, IBinder token) { 6763 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 6764 "Do not have permission in call getContentProviderExternal()"); 6765 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 6766 false, true, "getContentProvider", null); 6767 return getContentProviderExternalUnchecked(name, token, userId); 6768 } 6769 6770 private ContentProviderHolder getContentProviderExternalUnchecked(String name, 6771 IBinder token, int userId) { 6772 return getContentProviderImpl(null, name, token, true, userId); 6773 } 6774 6775 /** 6776 * Drop a content provider from a ProcessRecord's bookkeeping 6777 */ 6778 public void removeContentProvider(IBinder connection, boolean stable) { 6779 enforceNotIsolatedCaller("removeContentProvider"); 6780 synchronized (this) { 6781 ContentProviderConnection conn; 6782 try { 6783 conn = (ContentProviderConnection)connection; 6784 } catch (ClassCastException e) { 6785 String msg ="removeContentProvider: " + connection 6786 + " not a ContentProviderConnection"; 6787 Slog.w(TAG, msg); 6788 throw new IllegalArgumentException(msg); 6789 } 6790 if (conn == null) { 6791 throw new NullPointerException("connection is null"); 6792 } 6793 if (decProviderCountLocked(conn, null, null, stable)) { 6794 updateOomAdjLocked(); 6795 } 6796 } 6797 } 6798 6799 public void removeContentProviderExternal(String name, IBinder token) { 6800 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 6801 "Do not have permission in call removeContentProviderExternal()"); 6802 removeContentProviderExternalUnchecked(name, token, UserHandle.getCallingUserId()); 6803 } 6804 6805 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) { 6806 synchronized (this) { 6807 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId); 6808 if(cpr == null) { 6809 //remove from mProvidersByClass 6810 if(localLOGV) Slog.v(TAG, name+" content provider not found in providers list"); 6811 return; 6812 } 6813 6814 //update content provider record entry info 6815 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name); 6816 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId); 6817 if (localCpr.hasExternalProcessHandles()) { 6818 if (localCpr.removeExternalProcessHandleLocked(token)) { 6819 updateOomAdjLocked(); 6820 } else { 6821 Slog.e(TAG, "Attmpt to remove content provider " + localCpr 6822 + " with no external reference for token: " 6823 + token + "."); 6824 } 6825 } else { 6826 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr 6827 + " with no external references."); 6828 } 6829 } 6830 } 6831 6832 public final void publishContentProviders(IApplicationThread caller, 6833 List<ContentProviderHolder> providers) { 6834 if (providers == null) { 6835 return; 6836 } 6837 6838 enforceNotIsolatedCaller("publishContentProviders"); 6839 synchronized (this) { 6840 final ProcessRecord r = getRecordForAppLocked(caller); 6841 if (DEBUG_MU) 6842 Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid); 6843 if (r == null) { 6844 throw new SecurityException( 6845 "Unable to find app for caller " + caller 6846 + " (pid=" + Binder.getCallingPid() 6847 + ") when publishing content providers"); 6848 } 6849 6850 final long origId = Binder.clearCallingIdentity(); 6851 6852 final int N = providers.size(); 6853 for (int i=0; i<N; i++) { 6854 ContentProviderHolder src = providers.get(i); 6855 if (src == null || src.info == null || src.provider == null) { 6856 continue; 6857 } 6858 ContentProviderRecord dst = r.pubProviders.get(src.info.name); 6859 if (DEBUG_MU) 6860 Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid); 6861 if (dst != null) { 6862 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name); 6863 mProviderMap.putProviderByClass(comp, dst); 6864 String names[] = dst.info.authority.split(";"); 6865 for (in