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.Manifest.permission.INTERACT_ACROSS_USERS; 20 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL; 21 import static android.Manifest.permission.START_TASKS_FROM_RECENTS; 22 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 23 import static com.android.internal.util.XmlUtils.readBooleanAttribute; 24 import static com.android.internal.util.XmlUtils.readIntAttribute; 25 import static com.android.internal.util.XmlUtils.readLongAttribute; 26 import static com.android.internal.util.XmlUtils.writeBooleanAttribute; 27 import static com.android.internal.util.XmlUtils.writeIntAttribute; 28 import static com.android.internal.util.XmlUtils.writeLongAttribute; 29 import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST; 30 import static com.android.server.am.ActivityManagerDebugConfig.*; 31 import static com.android.server.am.ActivityStackSupervisor.HOME_STACK_ID; 32 import static com.android.server.am.TaskRecord.INVALID_TASK_ID; 33 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK; 34 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV; 35 import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE; 36 import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT; 37 import static org.xmlpull.v1.XmlPullParser.START_TAG; 38 39 import android.Manifest; 40 import android.app.AppOpsManager; 41 import android.app.ApplicationThreadNative; 42 import android.app.BroadcastOptions; 43 import android.app.IActivityContainer; 44 import android.app.IActivityContainerCallback; 45 import android.app.IAppTask; 46 import android.app.ITaskStackListener; 47 import android.app.ProfilerInfo; 48 import android.app.assist.AssistContent; 49 import android.app.assist.AssistStructure; 50 import android.app.usage.UsageEvents; 51 import android.app.usage.UsageStatsManagerInternal; 52 import android.appwidget.AppWidgetManager; 53 import android.content.pm.PermissionInfo; 54 import android.content.res.Resources; 55 import android.graphics.Bitmap; 56 import android.graphics.Point; 57 import android.graphics.Rect; 58 import android.os.BatteryStats; 59 import android.os.PersistableBundle; 60 import android.os.PowerManager; 61 import android.os.Trace; 62 import android.os.TransactionTooLargeException; 63 import android.os.WorkSource; 64 import android.os.storage.IMountService; 65 import android.os.storage.MountServiceInternal; 66 import android.os.storage.StorageManager; 67 import android.service.voice.IVoiceInteractionSession; 68 import android.service.voice.VoiceInteractionSession; 69 import android.util.ArrayMap; 70 import android.util.ArraySet; 71 import android.util.DebugUtils; 72 import android.util.SparseIntArray; 73 import android.view.Display; 74 75 import com.android.internal.R; 76 import com.android.internal.annotations.GuardedBy; 77 import com.android.internal.app.AssistUtils; 78 import com.android.internal.app.DumpHeapActivity; 79 import com.android.internal.app.IAppOpsService; 80 import com.android.internal.app.IVoiceInteractor; 81 import com.android.internal.app.ProcessMap; 82 import com.android.internal.app.ProcessStats; 83 import com.android.internal.os.BackgroundThread; 84 import com.android.internal.os.BatteryStatsImpl; 85 import com.android.internal.os.IResultReceiver; 86 import com.android.internal.os.ProcessCpuTracker; 87 import com.android.internal.os.TransferPipe; 88 import com.android.internal.os.Zygote; 89 import com.android.internal.util.ArrayUtils; 90 import com.android.internal.util.FastPrintWriter; 91 import com.android.internal.util.FastXmlSerializer; 92 import com.android.internal.util.MemInfoReader; 93 import com.android.internal.util.Preconditions; 94 import com.android.server.AppOpsService; 95 import com.android.server.AttributeCache; 96 import com.android.server.DeviceIdleController; 97 import com.android.server.IntentResolver; 98 import com.android.server.LocalServices; 99 import com.android.server.ServiceThread; 100 import com.android.server.SystemService; 101 import com.android.server.SystemServiceManager; 102 import com.android.server.Watchdog; 103 import com.android.server.am.ActivityStack.ActivityState; 104 import com.android.server.firewall.IntentFirewall; 105 import com.android.server.pm.Installer; 106 import com.android.server.pm.UserManagerService; 107 import com.android.server.statusbar.StatusBarManagerInternal; 108 import com.android.server.wm.AppTransition; 109 import com.android.server.wm.WindowManagerService; 110 import com.google.android.collect.Lists; 111 import com.google.android.collect.Maps; 112 113 import libcore.io.IoUtils; 114 import libcore.util.EmptyArray; 115 116 import org.xmlpull.v1.XmlPullParser; 117 import org.xmlpull.v1.XmlPullParserException; 118 import org.xmlpull.v1.XmlSerializer; 119 120 import android.app.Activity; 121 import android.app.ActivityManager; 122 import android.app.ActivityManager.RunningTaskInfo; 123 import android.app.ActivityManager.StackInfo; 124 import android.app.ActivityManagerInternal; 125 import android.app.ActivityManagerInternal.SleepToken; 126 import android.app.ActivityManagerNative; 127 import android.app.ActivityOptions; 128 import android.app.ActivityThread; 129 import android.app.AlertDialog; 130 import android.app.AppGlobals; 131 import android.app.ApplicationErrorReport; 132 import android.app.Dialog; 133 import android.app.IActivityController; 134 import android.app.IApplicationThread; 135 import android.app.IInstrumentationWatcher; 136 import android.app.INotificationManager; 137 import android.app.IProcessObserver; 138 import android.app.IServiceConnection; 139 import android.app.IStopUserCallback; 140 import android.app.IUidObserver; 141 import android.app.IUiAutomationConnection; 142 import android.app.IUserSwitchObserver; 143 import android.app.Instrumentation; 144 import android.app.Notification; 145 import android.app.NotificationManager; 146 import android.app.PendingIntent; 147 import android.app.backup.IBackupManager; 148 import android.app.admin.DevicePolicyManager; 149 import android.content.ActivityNotFoundException; 150 import android.content.BroadcastReceiver; 151 import android.content.ClipData; 152 import android.content.ComponentCallbacks2; 153 import android.content.ComponentName; 154 import android.content.ContentProvider; 155 import android.content.ContentResolver; 156 import android.content.Context; 157 import android.content.DialogInterface; 158 import android.content.IContentProvider; 159 import android.content.IIntentReceiver; 160 import android.content.IIntentSender; 161 import android.content.Intent; 162 import android.content.IntentFilter; 163 import android.content.IntentSender; 164 import android.content.pm.ActivityInfo; 165 import android.content.pm.ApplicationInfo; 166 import android.content.pm.ConfigurationInfo; 167 import android.content.pm.IPackageDataObserver; 168 import android.content.pm.IPackageManager; 169 import android.content.pm.InstrumentationInfo; 170 import android.content.pm.PackageInfo; 171 import android.content.pm.PackageManager; 172 import android.content.pm.ParceledListSlice; 173 import android.content.pm.UserInfo; 174 import android.content.pm.PackageManager.NameNotFoundException; 175 import android.content.pm.PathPermission; 176 import android.content.pm.ProviderInfo; 177 import android.content.pm.ResolveInfo; 178 import android.content.pm.ServiceInfo; 179 import android.content.res.CompatibilityInfo; 180 import android.content.res.Configuration; 181 import android.net.Proxy; 182 import android.net.ProxyInfo; 183 import android.net.Uri; 184 import android.os.Binder; 185 import android.os.Build; 186 import android.os.Bundle; 187 import android.os.Debug; 188 import android.os.DropBoxManager; 189 import android.os.Environment; 190 import android.os.FactoryTest; 191 import android.os.FileObserver; 192 import android.os.FileUtils; 193 import android.os.Handler; 194 import android.os.IBinder; 195 import android.os.IPermissionController; 196 import android.os.IProcessInfoService; 197 import android.os.IRemoteCallback; 198 import android.os.IUserManager; 199 import android.os.Looper; 200 import android.os.Message; 201 import android.os.Parcel; 202 import android.os.ParcelFileDescriptor; 203 import android.os.PowerManagerInternal; 204 import android.os.Process; 205 import android.os.RemoteCallbackList; 206 import android.os.RemoteException; 207 import android.os.SELinux; 208 import android.os.ServiceManager; 209 import android.os.StrictMode; 210 import android.os.SystemClock; 211 import android.os.SystemProperties; 212 import android.os.UpdateLock; 213 import android.os.UserHandle; 214 import android.os.UserManager; 215 import android.provider.Settings; 216 import android.telecom.TelecomManager; 217 import android.text.format.DateUtils; 218 import android.text.format.Time; 219 import android.util.AtomicFile; 220 import android.util.EventLog; 221 import android.util.Log; 222 import android.util.Pair; 223 import android.util.PrintWriterPrinter; 224 import android.util.Slog; 225 import android.util.SparseArray; 226 import android.util.TimeUtils; 227 import android.util.Xml; 228 import android.view.Gravity; 229 import android.view.LayoutInflater; 230 import android.view.View; 231 import android.view.WindowManager; 232 233 import dalvik.system.VMRuntime; 234 235 import java.io.BufferedInputStream; 236 import java.io.BufferedOutputStream; 237 import java.io.DataInputStream; 238 import java.io.DataOutputStream; 239 import java.io.File; 240 import java.io.FileDescriptor; 241 import java.io.FileInputStream; 242 import java.io.FileNotFoundException; 243 import java.io.FileOutputStream; 244 import java.io.IOException; 245 import java.io.InputStreamReader; 246 import java.io.PrintWriter; 247 import java.io.StringWriter; 248 import java.lang.ref.WeakReference; 249 import java.nio.charset.StandardCharsets; 250 import java.util.ArrayList; 251 import java.util.Arrays; 252 import java.util.Collections; 253 import java.util.Comparator; 254 import java.util.HashMap; 255 import java.util.HashSet; 256 import java.util.Iterator; 257 import java.util.List; 258 import java.util.Locale; 259 import java.util.Map; 260 import java.util.Set; 261 import java.util.concurrent.atomic.AtomicBoolean; 262 import java.util.concurrent.atomic.AtomicLong; 263 264 public final class ActivityManagerService extends ActivityManagerNative 265 implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback { 266 267 // File that stores last updated system version and called preboot receivers 268 static final String CALLED_PRE_BOOTS_FILENAME = "called_pre_boots.dat"; 269 270 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityManagerService" : TAG_AM; 271 private static final String TAG_BACKUP = TAG + POSTFIX_BACKUP; 272 private static final String TAG_BROADCAST = TAG + POSTFIX_BROADCAST; 273 private static final String TAG_CLEANUP = TAG + POSTFIX_CLEANUP; 274 private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION; 275 private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS; 276 private static final String TAG_IMMERSIVE = TAG + POSTFIX_IMMERSIVE; 277 private static final String TAG_LOCKSCREEN = TAG + POSTFIX_LOCKSCREEN; 278 private static final String TAG_LOCKTASK = TAG + POSTFIX_LOCKTASK; 279 private static final String TAG_LRU = TAG + POSTFIX_LRU; 280 private static final String TAG_MU = TAG + POSTFIX_MU; 281 private static final String TAG_OOM_ADJ = TAG + POSTFIX_OOM_ADJ; 282 private static final String TAG_POWER = TAG + POSTFIX_POWER; 283 private static final String TAG_PROCESS_OBSERVERS = TAG + POSTFIX_PROCESS_OBSERVERS; 284 private static final String TAG_PROCESSES = TAG + POSTFIX_PROCESSES; 285 private static final String TAG_PROVIDER = TAG + POSTFIX_PROVIDER; 286 private static final String TAG_PSS = TAG + POSTFIX_PSS; 287 private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS; 288 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE; 289 private static final String TAG_STACK = TAG + POSTFIX_STACK; 290 private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH; 291 private static final String TAG_UID_OBSERVERS = TAG + POSTFIX_UID_OBSERVERS; 292 private static final String TAG_URI_PERMISSION = TAG + POSTFIX_URI_PERMISSION; 293 private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY; 294 private static final String TAG_VISIBLE_BEHIND = TAG + POSTFIX_VISIBLE_BEHIND; 295 296 /** Control over CPU and battery monitoring */ 297 // write battery stats every 30 minutes. 298 static final long BATTERY_STATS_TIME = 30 * 60 * 1000; 299 static final boolean MONITOR_CPU_USAGE = true; 300 // don't sample cpu less than every 5 seconds. 301 static final long MONITOR_CPU_MIN_TIME = 5 * 1000; 302 // wait possibly forever for next cpu sample. 303 static final long MONITOR_CPU_MAX_TIME = 0x0fffffff; 304 static final boolean MONITOR_THREAD_CPU_USAGE = false; 305 306 // The flags that are set for all calls we make to the package manager. 307 static final int STOCK_PM_FLAGS = PackageManager.GET_SHARED_LIBRARY_FILES; 308 309 private static final String SYSTEM_DEBUGGABLE = "ro.debuggable"; 310 311 static final boolean IS_USER_BUILD = "user".equals(Build.TYPE); 312 313 // Amount of time after a call to stopAppSwitches() during which we will 314 // prevent further untrusted switches from happening. 315 static final long APP_SWITCH_DELAY_TIME = 5*1000; 316 317 // How long we wait for a launched process to attach to the activity manager 318 // before we decide it's never going to come up for real. 319 static final int PROC_START_TIMEOUT = 10*1000; 320 // How long we wait for an attached process to publish its content providers 321 // before we decide it must be hung. 322 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT = 10*1000; 323 324 // How long we wait for a launched process to attach to the activity manager 325 // before we decide it's never going to come up for real, when the process was 326 // started with a wrapper for instrumentation (such as Valgrind) because it 327 // could take much longer than usual. 328 static final int PROC_START_TIMEOUT_WITH_WRAPPER = 1200*1000; 329 330 // How long to wait after going idle before forcing apps to GC. 331 static final int GC_TIMEOUT = 5*1000; 332 333 // The minimum amount of time between successive GC requests for a process. 334 static final int GC_MIN_INTERVAL = 60*1000; 335 336 // The minimum amount of time between successive PSS requests for a process. 337 static final int FULL_PSS_MIN_INTERVAL = 10*60*1000; 338 339 // The minimum amount of time between successive PSS requests for a process 340 // when the request is due to the memory state being lowered. 341 static final int FULL_PSS_LOWERED_INTERVAL = 2*60*1000; 342 343 // The rate at which we check for apps using excessive power -- 15 mins. 344 static final int POWER_CHECK_DELAY = (DEBUG_POWER_QUICK ? 2 : 15) * 60*1000; 345 346 // The minimum sample duration we will allow before deciding we have 347 // enough data on wake locks to start killing things. 348 static final int WAKE_LOCK_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 349 350 // The minimum sample duration we will allow before deciding we have 351 // enough data on CPU usage to start killing things. 352 static final int CPU_MIN_CHECK_DURATION = (DEBUG_POWER_QUICK ? 1 : 5) * 60*1000; 353 354 // How long we allow a receiver to run before giving up on it. 355 static final int BROADCAST_FG_TIMEOUT = 10*1000; 356 static final int BROADCAST_BG_TIMEOUT = 60*1000; 357 358 // How long we wait until we timeout on key dispatching. 359 static final int KEY_DISPATCHING_TIMEOUT = 5*1000; 360 361 // How long we wait until we timeout on key dispatching during instrumentation. 362 static final int INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT = 60*1000; 363 364 // Amount of time we wait for observers to handle a user switch before 365 // giving up on them and unfreezing the screen. 366 static final int USER_SWITCH_TIMEOUT = 2*1000; 367 368 // This is the amount of time an app needs to be running a foreground service before 369 // we will consider it to be doing interaction for usage stats. 370 static final int SERVICE_USAGE_INTERACTION_TIME = 30*60*1000; 371 372 // Maximum amount of time we will allow to elapse before re-reporting usage stats 373 // interaction with foreground processes. 374 static final long USAGE_STATS_INTERACTION_INTERVAL = 24*60*60*1000L; 375 376 // Maximum number of users we allow to be running at a time. 377 static final int MAX_RUNNING_USERS = 3; 378 379 // How long to wait in getAssistContextExtras for the activity and foreground services 380 // to respond with the result. 381 static final int PENDING_ASSIST_EXTRAS_TIMEOUT = 500; 382 383 // How long top wait when going through the modern assist (which doesn't need to block 384 // on getting this result before starting to launch its UI). 385 static final int PENDING_ASSIST_EXTRAS_LONG_TIMEOUT = 2000; 386 387 // Maximum number of persisted Uri grants a package is allowed 388 static final int MAX_PERSISTED_URI_GRANTS = 128; 389 390 static final int MY_PID = Process.myPid(); 391 392 static final String[] EMPTY_STRING_ARRAY = new String[0]; 393 394 // How many bytes to write into the dropbox log before truncating 395 static final int DROPBOX_MAX_SIZE = 256 * 1024; 396 397 // Access modes for handleIncomingUser. 398 static final int ALLOW_NON_FULL = 0; 399 static final int ALLOW_NON_FULL_IN_PROFILE = 1; 400 static final int ALLOW_FULL_ONLY = 2; 401 402 static final int LAST_PREBOOT_DELIVERED_FILE_VERSION = 10000; 403 404 // Delay in notifying task stack change listeners (in millis) 405 static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY = 1000; 406 407 // Necessary ApplicationInfo flags to mark an app as persistent 408 private static final int PERSISTENT_MASK = 409 ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PERSISTENT; 410 411 412 // Delay to disable app launch boost 413 static final int APP_BOOST_MESSAGE_DELAY = 3000; 414 // Lower delay than APP_BOOST_MESSAGE_DELAY to disable the boost 415 static final int APP_BOOST_TIMEOUT = 2500; 416 nativeMigrateToBoost()417 private static native int nativeMigrateToBoost(); nativeMigrateFromBoost()418 private static native int nativeMigrateFromBoost(); 419 private boolean mIsBoosted = false; 420 private long mBoostStartTime = 0; 421 422 /** All system services */ 423 SystemServiceManager mSystemServiceManager; 424 425 private Installer mInstaller; 426 427 /** Run all ActivityStacks through this */ 428 ActivityStackSupervisor mStackSupervisor; 429 430 /** Task stack change listeners. */ 431 private RemoteCallbackList<ITaskStackListener> mTaskStackListeners = 432 new RemoteCallbackList<ITaskStackListener>(); 433 434 public IntentFirewall mIntentFirewall; 435 436 // Whether we should show our dialogs (ANR, crash, etc) or just perform their 437 // default actuion automatically. Important for devices without direct input 438 // devices. 439 private boolean mShowDialogs = true; 440 441 BroadcastQueue mFgBroadcastQueue; 442 BroadcastQueue mBgBroadcastQueue; 443 // Convenient for easy iteration over the queues. Foreground is first 444 // so that dispatch of foreground broadcasts gets precedence. 445 final BroadcastQueue[] mBroadcastQueues = new BroadcastQueue[2]; 446 broadcastQueueForIntent(Intent intent)447 BroadcastQueue broadcastQueueForIntent(Intent intent) { 448 final boolean isFg = (intent.getFlags() & Intent.FLAG_RECEIVER_FOREGROUND) != 0; 449 if (DEBUG_BROADCAST_BACKGROUND) Slog.i(TAG_BROADCAST, 450 "Broadcast intent " + intent + " on " 451 + (isFg ? "foreground" : "background") + " queue"); 452 return (isFg) ? mFgBroadcastQueue : mBgBroadcastQueue; 453 } 454 455 /** 456 * Activity we have told the window manager to have key focus. 457 */ 458 ActivityRecord mFocusedActivity = null; 459 460 /** 461 * User id of the last activity mFocusedActivity was set to. 462 */ 463 private int mLastFocusedUserId; 464 465 /** 466 * If non-null, we are tracking the time the user spends in the currently focused app. 467 */ 468 private AppTimeTracker mCurAppTimeTracker; 469 470 /** 471 * List of intents that were used to start the most recent tasks. 472 */ 473 private final RecentTasks mRecentTasks; 474 475 /** 476 * For addAppTask: cached of the last activity component that was added. 477 */ 478 ComponentName mLastAddedTaskComponent; 479 480 /** 481 * For addAppTask: cached of the last activity uid that was added. 482 */ 483 int mLastAddedTaskUid; 484 485 /** 486 * For addAppTask: cached of the last ActivityInfo that was added. 487 */ 488 ActivityInfo mLastAddedTaskActivity; 489 490 /** 491 * List of packages whitelisted by DevicePolicyManager for locktask. Indexed by userId. 492 */ 493 SparseArray<String[]> mLockTaskPackages = new SparseArray<>(); 494 495 /** 496 * The package name of the DeviceOwner. This package is not permitted to have its data cleared. 497 */ 498 String mDeviceOwnerName; 499 500 public class PendingAssistExtras extends Binder implements Runnable { 501 public final ActivityRecord activity; 502 public final Bundle extras; 503 public final Intent intent; 504 public final String hint; 505 public final IResultReceiver receiver; 506 public final int userHandle; 507 public boolean haveResult = false; 508 public Bundle result = null; 509 public AssistStructure structure = null; 510 public AssistContent content = null; PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent, String _hint, IResultReceiver _receiver, int _userHandle)511 public PendingAssistExtras(ActivityRecord _activity, Bundle _extras, Intent _intent, 512 String _hint, IResultReceiver _receiver, int _userHandle) { 513 activity = _activity; 514 extras = _extras; 515 intent = _intent; 516 hint = _hint; 517 receiver = _receiver; 518 userHandle = _userHandle; 519 } 520 @Override run()521 public void run() { 522 Slog.w(TAG, "getAssistContextExtras failed: timeout retrieving from " + activity); 523 synchronized (this) { 524 haveResult = true; 525 notifyAll(); 526 } 527 pendingAssistExtrasTimedOut(this); 528 } 529 } 530 531 final ArrayList<PendingAssistExtras> mPendingAssistExtras 532 = new ArrayList<PendingAssistExtras>(); 533 534 /** 535 * Process management. 536 */ 537 final ProcessList mProcessList = new ProcessList(); 538 539 /** 540 * All of the applications we currently have running organized by name. 541 * The keys are strings of the application package name (as 542 * returned by the package manager), and the keys are ApplicationRecord 543 * objects. 544 */ 545 final ProcessMap<ProcessRecord> mProcessNames = new ProcessMap<ProcessRecord>(); 546 547 /** 548 * Tracking long-term execution of processes to look for abuse and other 549 * bad app behavior. 550 */ 551 final ProcessStatsService mProcessStats; 552 553 /** 554 * The currently running isolated processes. 555 */ 556 final SparseArray<ProcessRecord> mIsolatedProcesses = new SparseArray<ProcessRecord>(); 557 558 /** 559 * Counter for assigning isolated process uids, to avoid frequently reusing the 560 * same ones. 561 */ 562 int mNextIsolatedProcessUid = 0; 563 564 /** 565 * The currently running heavy-weight process, if any. 566 */ 567 ProcessRecord mHeavyWeightProcess = null; 568 569 /** 570 * The last time that various processes have crashed. 571 */ 572 final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<Long>(); 573 574 /** 575 * Information about a process that is currently marked as bad. 576 */ 577 static final class BadProcessInfo { BadProcessInfo(long time, String shortMsg, String longMsg, String stack)578 BadProcessInfo(long time, String shortMsg, String longMsg, String stack) { 579 this.time = time; 580 this.shortMsg = shortMsg; 581 this.longMsg = longMsg; 582 this.stack = stack; 583 } 584 585 final long time; 586 final String shortMsg; 587 final String longMsg; 588 final String stack; 589 } 590 591 /** 592 * Set of applications that we consider to be bad, and will reject 593 * incoming broadcasts from (which the user has no control over). 594 * Processes are added to this set when they have crashed twice within 595 * a minimum amount of time; they are removed from it when they are 596 * later restarted (hopefully due to some user action). The value is the 597 * time it was added to the list. 598 */ 599 final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<BadProcessInfo>(); 600 601 /** 602 * All of the processes we currently have running organized by pid. 603 * The keys are the pid running the application. 604 * 605 * <p>NOTE: This object is protected by its own lock, NOT the global 606 * activity manager lock! 607 */ 608 final SparseArray<ProcessRecord> mPidsSelfLocked = new SparseArray<ProcessRecord>(); 609 610 /** 611 * All of the processes that have been forced to be foreground. The key 612 * is the pid of the caller who requested it (we hold a death 613 * link on it). 614 */ 615 abstract class ForegroundToken implements IBinder.DeathRecipient { 616 int pid; 617 IBinder token; 618 } 619 final SparseArray<ForegroundToken> mForegroundProcesses = new SparseArray<ForegroundToken>(); 620 621 /** 622 * List of records for processes that someone had tried to start before the 623 * system was ready. We don't start them at that point, but ensure they 624 * are started by the time booting is complete. 625 */ 626 final ArrayList<ProcessRecord> mProcessesOnHold = new ArrayList<ProcessRecord>(); 627 628 /** 629 * List of persistent applications that are in the process 630 * of being started. 631 */ 632 final ArrayList<ProcessRecord> mPersistentStartingProcesses = new ArrayList<ProcessRecord>(); 633 634 /** 635 * Processes that are being forcibly torn down. 636 */ 637 final ArrayList<ProcessRecord> mRemovedProcesses = new ArrayList<ProcessRecord>(); 638 639 /** 640 * List of running applications, sorted by recent usage. 641 * The first entry in the list is the least recently used. 642 */ 643 final ArrayList<ProcessRecord> mLruProcesses = new ArrayList<ProcessRecord>(); 644 645 /** 646 * Where in mLruProcesses that the processes hosting activities start. 647 */ 648 int mLruProcessActivityStart = 0; 649 650 /** 651 * Where in mLruProcesses that the processes hosting services start. 652 * This is after (lower index) than mLruProcessesActivityStart. 653 */ 654 int mLruProcessServiceStart = 0; 655 656 /** 657 * List of processes that should gc as soon as things are idle. 658 */ 659 final ArrayList<ProcessRecord> mProcessesToGc = new ArrayList<ProcessRecord>(); 660 661 /** 662 * Processes we want to collect PSS data from. 663 */ 664 final ArrayList<ProcessRecord> mPendingPssProcesses = new ArrayList<ProcessRecord>(); 665 666 /** 667 * Last time we requested PSS data of all processes. 668 */ 669 long mLastFullPssTime = SystemClock.uptimeMillis(); 670 671 /** 672 * If set, the next time we collect PSS data we should do a full collection 673 * with data from native processes and the kernel. 674 */ 675 boolean mFullPssPending = false; 676 677 /** 678 * This is the process holding what we currently consider to be 679 * the "home" activity. 680 */ 681 ProcessRecord mHomeProcess; 682 683 /** 684 * This is the process holding the activity the user last visited that 685 * is in a different process from the one they are currently in. 686 */ 687 ProcessRecord mPreviousProcess; 688 689 /** 690 * The time at which the previous process was last visible. 691 */ 692 long mPreviousProcessVisibleTime; 693 694 /** 695 * Track all uids that have actively running processes. 696 */ 697 final SparseArray<UidRecord> mActiveUids = new SparseArray<>(); 698 699 /** 700 * Which users have been started, so are allowed to run code. 701 */ 702 final SparseArray<UserState> mStartedUsers = new SparseArray<>(); 703 704 /** 705 * LRU list of history of current users. Most recently current is at the end. 706 */ 707 final ArrayList<Integer> mUserLru = new ArrayList<Integer>(); 708 709 /** 710 * Constant array of the users that are currently started. 711 */ 712 int[] mStartedUserArray = new int[] { 0 }; 713 714 /** 715 * Registered observers of the user switching mechanics. 716 */ 717 final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers 718 = new RemoteCallbackList<IUserSwitchObserver>(); 719 720 /** 721 * Currently active user switch. 722 */ 723 Object mCurUserSwitchCallback; 724 725 /** 726 * Packages that the user has asked to have run in screen size 727 * compatibility mode instead of filling the screen. 728 */ 729 final CompatModePackages mCompatModePackages; 730 731 /** 732 * Set of IntentSenderRecord objects that are currently active. 733 */ 734 final HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>> mIntentSenderRecords 735 = new HashMap<PendingIntentRecord.Key, WeakReference<PendingIntentRecord>>(); 736 737 /** 738 * Fingerprints (hashCode()) of stack traces that we've 739 * already logged DropBox entries for. Guarded by itself. If 740 * something (rogue user app) forces this over 741 * MAX_DUP_SUPPRESSED_STACKS entries, the contents are cleared. 742 */ 743 private final HashSet<Integer> mAlreadyLoggedViolatedStacks = new HashSet<Integer>(); 744 private static final int MAX_DUP_SUPPRESSED_STACKS = 5000; 745 746 /** 747 * Strict Mode background batched logging state. 748 * 749 * The string buffer is guarded by itself, and its lock is also 750 * used to determine if another batched write is already 751 * in-flight. 752 */ 753 private final StringBuilder mStrictModeBuffer = new StringBuilder(); 754 755 /** 756 * Keeps track of all IIntentReceivers that have been registered for broadcasts. 757 * Hash keys are the receiver IBinder, hash value is a ReceiverList. 758 */ 759 final HashMap<IBinder, ReceiverList> mRegisteredReceivers = new HashMap<>(); 760 761 /** 762 * Resolver for broadcast intents to registered receivers. 763 * Holds BroadcastFilter (subclass of IntentFilter). 764 */ 765 final IntentResolver<BroadcastFilter, BroadcastFilter> mReceiverResolver 766 = new IntentResolver<BroadcastFilter, BroadcastFilter>() { 767 @Override 768 protected boolean allowFilterResult( 769 BroadcastFilter filter, List<BroadcastFilter> dest) { 770 IBinder target = filter.receiverList.receiver.asBinder(); 771 for (int i = dest.size() - 1; i >= 0; i--) { 772 if (dest.get(i).receiverList.receiver.asBinder() == target) { 773 return false; 774 } 775 } 776 return true; 777 } 778 779 @Override 780 protected BroadcastFilter newResult(BroadcastFilter filter, int match, int userId) { 781 if (userId == UserHandle.USER_ALL || filter.owningUserId == UserHandle.USER_ALL 782 || userId == filter.owningUserId) { 783 return super.newResult(filter, match, userId); 784 } 785 return null; 786 } 787 788 @Override 789 protected BroadcastFilter[] newArray(int size) { 790 return new BroadcastFilter[size]; 791 } 792 793 @Override 794 protected boolean isPackageForFilter(String packageName, BroadcastFilter filter) { 795 return packageName.equals(filter.packageName); 796 } 797 }; 798 799 /** 800 * State of all active sticky broadcasts per user. Keys are the action of the 801 * sticky Intent, values are an ArrayList of all broadcasted intents with 802 * that action (which should usually be one). The SparseArray is keyed 803 * by the user ID the sticky is for, and can include UserHandle.USER_ALL 804 * for stickies that are sent to all users. 805 */ 806 final SparseArray<ArrayMap<String, ArrayList<Intent>>> mStickyBroadcasts = 807 new SparseArray<ArrayMap<String, ArrayList<Intent>>>(); 808 809 final ActiveServices mServices; 810 811 final static class Association { 812 final int mSourceUid; 813 final String mSourceProcess; 814 final int mTargetUid; 815 final ComponentName mTargetComponent; 816 final String mTargetProcess; 817 818 int mCount; 819 long mTime; 820 821 int mNesting; 822 long mStartTime; 823 Association(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)824 Association(int sourceUid, String sourceProcess, int targetUid, 825 ComponentName targetComponent, String targetProcess) { 826 mSourceUid = sourceUid; 827 mSourceProcess = sourceProcess; 828 mTargetUid = targetUid; 829 mTargetComponent = targetComponent; 830 mTargetProcess = targetProcess; 831 } 832 } 833 834 /** 835 * When service association tracking is enabled, this is all of the associations we 836 * have seen. Mapping is target uid -> target component -> source uid -> source process name 837 * -> association data. 838 */ 839 final SparseArray<ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>>> 840 mAssociations = new SparseArray<>(); 841 boolean mTrackingAssociations; 842 843 /** 844 * Backup/restore process management 845 */ 846 String mBackupAppName = null; 847 BackupRecord mBackupTarget = null; 848 849 final ProviderMap mProviderMap; 850 851 /** 852 * List of content providers who have clients waiting for them. The 853 * application is currently being launched and the provider will be 854 * removed from this list once it is published. 855 */ 856 final ArrayList<ContentProviderRecord> mLaunchingProviders 857 = new ArrayList<ContentProviderRecord>(); 858 859 /** 860 * File storing persisted {@link #mGrantedUriPermissions}. 861 */ 862 private final AtomicFile mGrantFile; 863 864 /** XML constants used in {@link #mGrantFile} */ 865 private static final String TAG_URI_GRANTS = "uri-grants"; 866 private static final String TAG_URI_GRANT = "uri-grant"; 867 private static final String ATTR_USER_HANDLE = "userHandle"; 868 private static final String ATTR_SOURCE_USER_ID = "sourceUserId"; 869 private static final String ATTR_TARGET_USER_ID = "targetUserId"; 870 private static final String ATTR_SOURCE_PKG = "sourcePkg"; 871 private static final String ATTR_TARGET_PKG = "targetPkg"; 872 private static final String ATTR_URI = "uri"; 873 private static final String ATTR_MODE_FLAGS = "modeFlags"; 874 private static final String ATTR_CREATED_TIME = "createdTime"; 875 private static final String ATTR_PREFIX = "prefix"; 876 877 /** 878 * Global set of specific {@link Uri} permissions that have been granted. 879 * This optimized lookup structure maps from {@link UriPermission#targetUid} 880 * to {@link UriPermission#uri} to {@link UriPermission}. 881 */ 882 @GuardedBy("this") 883 private final SparseArray<ArrayMap<GrantUri, UriPermission>> 884 mGrantedUriPermissions = new SparseArray<ArrayMap<GrantUri, UriPermission>>(); 885 886 public static class GrantUri { 887 public final int sourceUserId; 888 public final Uri uri; 889 public boolean prefix; 890 GrantUri(int sourceUserId, Uri uri, boolean prefix)891 public GrantUri(int sourceUserId, Uri uri, boolean prefix) { 892 this.sourceUserId = sourceUserId; 893 this.uri = uri; 894 this.prefix = prefix; 895 } 896 897 @Override hashCode()898 public int hashCode() { 899 int hashCode = 1; 900 hashCode = 31 * hashCode + sourceUserId; 901 hashCode = 31 * hashCode + uri.hashCode(); 902 hashCode = 31 * hashCode + (prefix ? 1231 : 1237); 903 return hashCode; 904 } 905 906 @Override equals(Object o)907 public boolean equals(Object o) { 908 if (o instanceof GrantUri) { 909 GrantUri other = (GrantUri) o; 910 return uri.equals(other.uri) && (sourceUserId == other.sourceUserId) 911 && prefix == other.prefix; 912 } 913 return false; 914 } 915 916 @Override toString()917 public String toString() { 918 String result = Integer.toString(sourceUserId) + " @ " + uri.toString(); 919 if (prefix) result += " [prefix]"; 920 return result; 921 } 922 toSafeString()923 public String toSafeString() { 924 String result = Integer.toString(sourceUserId) + " @ " + uri.toSafeString(); 925 if (prefix) result += " [prefix]"; 926 return result; 927 } 928 resolve(int defaultSourceUserHandle, Uri uri)929 public static GrantUri resolve(int defaultSourceUserHandle, Uri uri) { 930 return new GrantUri(ContentProvider.getUserIdFromUri(uri, defaultSourceUserHandle), 931 ContentProvider.getUriWithoutUserId(uri), false); 932 } 933 } 934 935 CoreSettingsObserver mCoreSettingsObserver; 936 937 /** 938 * Thread-local storage used to carry caller permissions over through 939 * indirect content-provider access. 940 */ 941 private class Identity { 942 public final IBinder token; 943 public final int pid; 944 public final int uid; 945 Identity(IBinder _token, int _pid, int _uid)946 Identity(IBinder _token, int _pid, int _uid) { 947 token = _token; 948 pid = _pid; 949 uid = _uid; 950 } 951 } 952 953 private static final ThreadLocal<Identity> sCallerIdentity = new ThreadLocal<Identity>(); 954 955 /** 956 * All information we have collected about the runtime performance of 957 * any user id that can impact battery performance. 958 */ 959 final BatteryStatsService mBatteryStatsService; 960 961 /** 962 * Information about component usage 963 */ 964 UsageStatsManagerInternal mUsageStatsService; 965 966 /** 967 * Access to DeviceIdleController service. 968 */ 969 DeviceIdleController.LocalService mLocalDeviceIdleController; 970 971 /** 972 * Information about and control over application operations 973 */ 974 final AppOpsService mAppOpsService; 975 976 /** 977 * Save recent tasks information across reboots. 978 */ 979 final TaskPersister mTaskPersister; 980 981 /** 982 * Current configuration information. HistoryRecord objects are given 983 * a reference to this object to indicate which configuration they are 984 * currently running in, so this object must be kept immutable. 985 */ 986 Configuration mConfiguration = new Configuration(); 987 988 /** 989 * Current sequencing integer of the configuration, for skipping old 990 * configurations. 991 */ 992 int mConfigurationSeq = 0; 993 994 /** 995 * Hardware-reported OpenGLES version. 996 */ 997 final int GL_ES_VERSION; 998 999 /** 1000 * List of initialization arguments to pass to all processes when binding applications to them. 1001 * For example, references to the commonly used services. 1002 */ 1003 HashMap<String, IBinder> mAppBindArgs; 1004 1005 /** 1006 * Temporary to avoid allocations. Protected by main lock. 1007 */ 1008 final StringBuilder mStringBuilder = new StringBuilder(256); 1009 1010 /** 1011 * Used to control how we initialize the service. 1012 */ 1013 ComponentName mTopComponent; 1014 String mTopAction = Intent.ACTION_MAIN; 1015 String mTopData; 1016 boolean mProcessesReady = false; 1017 boolean mSystemReady = false; 1018 boolean mBooting = false; 1019 boolean mCallFinishBooting = false; 1020 boolean mBootAnimationComplete = false; 1021 boolean mWaitingUpdate = false; 1022 boolean mDidUpdate = false; 1023 boolean mOnBattery = false; 1024 boolean mLaunchWarningShown = false; 1025 1026 Context mContext; 1027 1028 int mFactoryTest; 1029 1030 boolean mCheckedForSetup; 1031 1032 /** 1033 * The time at which we will allow normal application switches again, 1034 * after a call to {@link #stopAppSwitches()}. 1035 */ 1036 long mAppSwitchesAllowedTime; 1037 1038 /** 1039 * This is set to true after the first switch after mAppSwitchesAllowedTime 1040 * is set; any switches after that will clear the time. 1041 */ 1042 boolean mDidAppSwitch; 1043 1044 /** 1045 * Last time (in realtime) at which we checked for power usage. 1046 */ 1047 long mLastPowerCheckRealtime; 1048 1049 /** 1050 * Last time (in uptime) at which we checked for power usage. 1051 */ 1052 long mLastPowerCheckUptime; 1053 1054 /** 1055 * Set while we are wanting to sleep, to prevent any 1056 * activities from being started/resumed. 1057 */ 1058 private boolean mSleeping = false; 1059 1060 /** 1061 * The process state used for processes that are running the top activities. 1062 * This changes between TOP and TOP_SLEEPING to following mSleeping. 1063 */ 1064 int mTopProcessState = ActivityManager.PROCESS_STATE_TOP; 1065 1066 /** 1067 * Set while we are running a voice interaction. This overrides 1068 * sleeping while it is active. 1069 */ 1070 private IVoiceInteractionSession mRunningVoice; 1071 1072 /** 1073 * For some direct access we need to power manager. 1074 */ 1075 PowerManagerInternal mLocalPowerManager; 1076 1077 /** 1078 * We want to hold a wake lock while running a voice interaction session, since 1079 * this may happen with the screen off and we need to keep the CPU running to 1080 * be able to continue to interact with the user. 1081 */ 1082 PowerManager.WakeLock mVoiceWakeLock; 1083 1084 /** 1085 * State of external calls telling us if the device is awake or asleep. 1086 */ 1087 private int mWakefulness = PowerManagerInternal.WAKEFULNESS_AWAKE; 1088 1089 /** 1090 * A list of tokens that cause the top activity to be put to sleep. 1091 * They are used by components that may hide and block interaction with underlying 1092 * activities. 1093 */ 1094 final ArrayList<SleepToken> mSleepTokens = new ArrayList<SleepToken>(); 1095 1096 static final int LOCK_SCREEN_HIDDEN = 0; 1097 static final int LOCK_SCREEN_LEAVING = 1; 1098 static final int LOCK_SCREEN_SHOWN = 2; 1099 /** 1100 * State of external call telling us if the lock screen is shown. 1101 */ 1102 int mLockScreenShown = LOCK_SCREEN_HIDDEN; 1103 1104 /** 1105 * Set if we are shutting down the system, similar to sleeping. 1106 */ 1107 boolean mShuttingDown = false; 1108 1109 /** 1110 * Current sequence id for oom_adj computation traversal. 1111 */ 1112 int mAdjSeq = 0; 1113 1114 /** 1115 * Current sequence id for process LRU updating. 1116 */ 1117 int mLruSeq = 0; 1118 1119 /** 1120 * Keep track of the non-cached/empty process we last found, to help 1121 * determine how to distribute cached/empty processes next time. 1122 */ 1123 int mNumNonCachedProcs = 0; 1124 1125 /** 1126 * Keep track of the number of cached hidden procs, to balance oom adj 1127 * distribution between those and empty procs. 1128 */ 1129 int mNumCachedHiddenProcs = 0; 1130 1131 /** 1132 * Keep track of the number of service processes we last found, to 1133 * determine on the next iteration which should be B services. 1134 */ 1135 int mNumServiceProcs = 0; 1136 int mNewNumAServiceProcs = 0; 1137 int mNewNumServiceProcs = 0; 1138 1139 /** 1140 * Allow the current computed overall memory level of the system to go down? 1141 * This is set to false when we are killing processes for reasons other than 1142 * memory management, so that the now smaller process list will not be taken as 1143 * an indication that memory is tighter. 1144 */ 1145 boolean mAllowLowerMemLevel = false; 1146 1147 /** 1148 * The last computed memory level, for holding when we are in a state that 1149 * processes are going away for other reasons. 1150 */ 1151 int mLastMemoryLevel = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 1152 1153 /** 1154 * The last total number of process we have, to determine if changes actually look 1155 * like a shrinking number of process due to lower RAM. 1156 */ 1157 int mLastNumProcesses; 1158 1159 /** 1160 * The uptime of the last time we performed idle maintenance. 1161 */ 1162 long mLastIdleTime = SystemClock.uptimeMillis(); 1163 1164 /** 1165 * Total time spent with RAM that has been added in the past since the last idle time. 1166 */ 1167 long mLowRamTimeSinceLastIdle = 0; 1168 1169 /** 1170 * If RAM is currently low, when that horrible situation started. 1171 */ 1172 long mLowRamStartTime = 0; 1173 1174 /** 1175 * For reporting to battery stats the current top application. 1176 */ 1177 private String mCurResumedPackage = null; 1178 private int mCurResumedUid = -1; 1179 1180 /** 1181 * For reporting to battery stats the apps currently running foreground 1182 * service. The ProcessMap is package/uid tuples; each of these contain 1183 * an array of the currently foreground processes. 1184 */ 1185 final ProcessMap<ArrayList<ProcessRecord>> mForegroundPackages 1186 = new ProcessMap<ArrayList<ProcessRecord>>(); 1187 1188 /** 1189 * This is set if we had to do a delayed dexopt of an app before launching 1190 * it, to increase the ANR timeouts in that case. 1191 */ 1192 boolean mDidDexOpt; 1193 1194 /** 1195 * Set if the systemServer made a call to enterSafeMode. 1196 */ 1197 boolean mSafeMode; 1198 1199 /** 1200 * If true, we are running under a test environment so will sample PSS from processes 1201 * much more rapidly to try to collect better data when the tests are rapidly 1202 * running through apps. 1203 */ 1204 boolean mTestPssMode = false; 1205 1206 String mDebugApp = null; 1207 boolean mWaitForDebugger = false; 1208 boolean mDebugTransient = false; 1209 String mOrigDebugApp = null; 1210 boolean mOrigWaitForDebugger = false; 1211 boolean mAlwaysFinishActivities = false; 1212 IActivityController mController = null; 1213 String mProfileApp = null; 1214 ProcessRecord mProfileProc = null; 1215 String mProfileFile; 1216 ParcelFileDescriptor mProfileFd; 1217 int mSamplingInterval = 0; 1218 boolean mAutoStopProfiler = false; 1219 int mProfileType = 0; 1220 String mOpenGlTraceApp = null; 1221 final ProcessMap<Pair<Long, String>> mMemWatchProcesses = new ProcessMap<>(); 1222 String mMemWatchDumpProcName; 1223 String mMemWatchDumpFile; 1224 int mMemWatchDumpPid; 1225 int mMemWatchDumpUid; 1226 1227 final long[] mTmpLong = new long[1]; 1228 1229 static final class ProcessChangeItem { 1230 static final int CHANGE_ACTIVITIES = 1<<0; 1231 static final int CHANGE_PROCESS_STATE = 1<<1; 1232 int changes; 1233 int uid; 1234 int pid; 1235 int processState; 1236 boolean foregroundActivities; 1237 } 1238 1239 final RemoteCallbackList<IProcessObserver> mProcessObservers = new RemoteCallbackList<>(); 1240 ProcessChangeItem[] mActiveProcessChanges = new ProcessChangeItem[5]; 1241 1242 final ArrayList<ProcessChangeItem> mPendingProcessChanges = new ArrayList<>(); 1243 final ArrayList<ProcessChangeItem> mAvailProcessChanges = new ArrayList<>(); 1244 1245 final RemoteCallbackList<IUidObserver> mUidObservers = new RemoteCallbackList<>(); 1246 UidRecord.ChangeItem[] mActiveUidChanges = new UidRecord.ChangeItem[5]; 1247 1248 final ArrayList<UidRecord.ChangeItem> mPendingUidChanges = new ArrayList<>(); 1249 final ArrayList<UidRecord.ChangeItem> mAvailUidChanges = new ArrayList<>(); 1250 1251 /** 1252 * Runtime CPU use collection thread. This object's lock is used to 1253 * perform synchronization with the thread (notifying it to run). 1254 */ 1255 final Thread mProcessCpuThread; 1256 1257 /** 1258 * Used to collect per-process CPU use for ANRs, battery stats, etc. 1259 * Must acquire this object's lock when accessing it. 1260 * NOTE: this lock will be held while doing long operations (trawling 1261 * through all processes in /proc), so it should never be acquired by 1262 * any critical paths such as when holding the main activity manager lock. 1263 */ 1264 final ProcessCpuTracker mProcessCpuTracker = new ProcessCpuTracker( 1265 MONITOR_THREAD_CPU_USAGE); 1266 final AtomicLong mLastCpuTime = new AtomicLong(0); 1267 final AtomicBoolean mProcessCpuMutexFree = new AtomicBoolean(true); 1268 1269 long mLastWriteTime = 0; 1270 1271 /** 1272 * Used to retain an update lock when the foreground activity is in 1273 * immersive mode. 1274 */ 1275 final UpdateLock mUpdateLock = new UpdateLock("immersive"); 1276 1277 /** 1278 * Set to true after the system has finished booting. 1279 */ 1280 boolean mBooted = false; 1281 1282 int mProcessLimit = ProcessList.MAX_CACHED_APPS; 1283 int mProcessLimitOverride = -1; 1284 1285 WindowManagerService mWindowManager; 1286 1287 final ActivityThread mSystemThread; 1288 1289 // Holds the current foreground user's id 1290 int mCurrentUserId = 0; 1291 // Holds the target user's id during a user switch 1292 int mTargetUserId = UserHandle.USER_NULL; 1293 // If there are multiple profiles for the current user, their ids are here 1294 // Currently only the primary user can have managed profiles 1295 int[] mCurrentProfileIds = new int[] {UserHandle.USER_OWNER}; // Accessed by ActivityStack 1296 1297 /** 1298 * Mapping from each known user ID to the profile group ID it is associated with. 1299 */ 1300 SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray(); 1301 1302 private UserManagerService mUserManager; 1303 1304 private final class AppDeathRecipient implements IBinder.DeathRecipient { 1305 final ProcessRecord mApp; 1306 final int mPid; 1307 final IApplicationThread mAppThread; 1308 AppDeathRecipient(ProcessRecord app, int pid, IApplicationThread thread)1309 AppDeathRecipient(ProcessRecord app, int pid, 1310 IApplicationThread thread) { 1311 if (DEBUG_ALL) Slog.v( 1312 TAG, "New death recipient " + this 1313 + " for thread " + thread.asBinder()); 1314 mApp = app; 1315 mPid = pid; 1316 mAppThread = thread; 1317 } 1318 1319 @Override binderDied()1320 public void binderDied() { 1321 if (DEBUG_ALL) Slog.v( 1322 TAG, "Death received in " + this 1323 + " for thread " + mAppThread.asBinder()); 1324 synchronized(ActivityManagerService.this) { 1325 appDiedLocked(mApp, mPid, mAppThread, true); 1326 } 1327 } 1328 } 1329 1330 static final int SHOW_ERROR_MSG = 1; 1331 static final int SHOW_NOT_RESPONDING_MSG = 2; 1332 static final int SHOW_FACTORY_ERROR_MSG = 3; 1333 static final int UPDATE_CONFIGURATION_MSG = 4; 1334 static final int GC_BACKGROUND_PROCESSES_MSG = 5; 1335 static final int WAIT_FOR_DEBUGGER_MSG = 6; 1336 static final int SERVICE_TIMEOUT_MSG = 12; 1337 static final int UPDATE_TIME_ZONE = 13; 1338 static final int SHOW_UID_ERROR_MSG = 14; 1339 static final int SHOW_FINGERPRINT_ERROR_MSG = 15; 1340 static final int PROC_START_TIMEOUT_MSG = 20; 1341 static final int DO_PENDING_ACTIVITY_LAUNCHES_MSG = 21; 1342 static final int KILL_APPLICATION_MSG = 22; 1343 static final int FINALIZE_PENDING_INTENT_MSG = 23; 1344 static final int POST_HEAVY_NOTIFICATION_MSG = 24; 1345 static final int CANCEL_HEAVY_NOTIFICATION_MSG = 25; 1346 static final int SHOW_STRICT_MODE_VIOLATION_MSG = 26; 1347 static final int CHECK_EXCESSIVE_WAKE_LOCKS_MSG = 27; 1348 static final int CLEAR_DNS_CACHE_MSG = 28; 1349 static final int UPDATE_HTTP_PROXY_MSG = 29; 1350 static final int SHOW_COMPAT_MODE_DIALOG_MSG = 30; 1351 static final int DISPATCH_PROCESSES_CHANGED = 31; 1352 static final int DISPATCH_PROCESS_DIED = 32; 1353 static final int REPORT_MEM_USAGE_MSG = 33; 1354 static final int REPORT_USER_SWITCH_MSG = 34; 1355 static final int CONTINUE_USER_SWITCH_MSG = 35; 1356 static final int USER_SWITCH_TIMEOUT_MSG = 36; 1357 static final int IMMERSIVE_MODE_LOCK_MSG = 37; 1358 static final int PERSIST_URI_GRANTS_MSG = 38; 1359 static final int REQUEST_ALL_PSS_MSG = 39; 1360 static final int START_PROFILES_MSG = 40; 1361 static final int UPDATE_TIME = 41; 1362 static final int SYSTEM_USER_START_MSG = 42; 1363 static final int SYSTEM_USER_CURRENT_MSG = 43; 1364 static final int ENTER_ANIMATION_COMPLETE_MSG = 44; 1365 static final int FINISH_BOOTING_MSG = 45; 1366 static final int START_USER_SWITCH_MSG = 46; 1367 static final int SEND_LOCALE_TO_MOUNT_DAEMON_MSG = 47; 1368 static final int DISMISS_DIALOG_MSG = 48; 1369 static final int NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG = 49; 1370 static final int NOTIFY_CLEARTEXT_NETWORK_MSG = 50; 1371 static final int POST_DUMP_HEAP_NOTIFICATION_MSG = 51; 1372 static final int DELETE_DUMPHEAP_MSG = 52; 1373 static final int FOREGROUND_PROFILE_CHANGED_MSG = 53; 1374 static final int DISPATCH_UIDS_CHANGED_MSG = 54; 1375 static final int REPORT_TIME_TRACKER_MSG = 55; 1376 static final int REPORT_USER_SWITCH_COMPLETE_MSG = 56; 1377 static final int SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG = 57; 1378 static final int APP_BOOST_DEACTIVATE_MSG = 58; 1379 static final int CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG = 59; 1380 1381 static final int FIRST_ACTIVITY_STACK_MSG = 100; 1382 static final int FIRST_BROADCAST_QUEUE_MSG = 200; 1383 static final int FIRST_COMPAT_MODE_MSG = 300; 1384 static final int FIRST_SUPERVISOR_STACK_MSG = 100; 1385 1386 CompatModeDialog mCompatModeDialog; 1387 long mLastMemUsageReportTime = 0; 1388 1389 /** 1390 * Flag whether the current user is a "monkey", i.e. whether 1391 * the UI is driven by a UI automation tool. 1392 */ 1393 private boolean mUserIsMonkey; 1394 1395 /** Flag whether the device has a Recents UI */ 1396 boolean mHasRecents; 1397 1398 /** The dimensions of the thumbnails in the Recents UI. */ 1399 int mThumbnailWidth; 1400 int mThumbnailHeight; 1401 1402 final ServiceThread mHandlerThread; 1403 final MainHandler mHandler; 1404 final UiHandler mUiHandler; 1405 1406 final class UiHandler extends Handler { UiHandler()1407 public UiHandler() { 1408 super(com.android.server.UiThread.get().getLooper(), null, true); 1409 } 1410 1411 @Override handleMessage(Message msg)1412 public void handleMessage(Message msg) { 1413 switch (msg.what) { 1414 case SHOW_ERROR_MSG: { 1415 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1416 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 1417 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 1418 synchronized (ActivityManagerService.this) { 1419 ProcessRecord proc = (ProcessRecord)data.get("app"); 1420 AppErrorResult res = (AppErrorResult) data.get("result"); 1421 if (proc != null && proc.crashDialog != null) { 1422 Slog.e(TAG, "App already has crash dialog: " + proc); 1423 if (res != null) { 1424 res.set(0); 1425 } 1426 return; 1427 } 1428 boolean isBackground = (UserHandle.getAppId(proc.uid) 1429 >= Process.FIRST_APPLICATION_UID 1430 && proc.pid != MY_PID); 1431 for (int userId : mCurrentProfileIds) { 1432 isBackground &= (proc.userId != userId); 1433 } 1434 if (isBackground && !showBackground) { 1435 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background"); 1436 if (res != null) { 1437 res.set(0); 1438 } 1439 return; 1440 } 1441 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1442 Dialog d = new AppErrorDialog(mContext, 1443 ActivityManagerService.this, res, proc); 1444 d.show(); 1445 proc.crashDialog = d; 1446 } else { 1447 // The device is asleep, so just pretend that the user 1448 // saw a crash dialog and hit "force quit". 1449 if (res != null) { 1450 res.set(0); 1451 } 1452 } 1453 } 1454 1455 ensureBootCompleted(); 1456 } break; 1457 case SHOW_NOT_RESPONDING_MSG: { 1458 synchronized (ActivityManagerService.this) { 1459 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1460 ProcessRecord proc = (ProcessRecord)data.get("app"); 1461 if (proc != null && proc.anrDialog != null) { 1462 Slog.e(TAG, "App already has anr dialog: " + proc); 1463 return; 1464 } 1465 1466 Intent intent = new Intent("android.intent.action.ANR"); 1467 if (!mProcessesReady) { 1468 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 1469 | Intent.FLAG_RECEIVER_FOREGROUND); 1470 } 1471 broadcastIntentLocked(null, null, intent, 1472 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 1473 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */); 1474 1475 if (mShowDialogs) { 1476 Dialog d = new AppNotRespondingDialog(ActivityManagerService.this, 1477 mContext, proc, (ActivityRecord)data.get("activity"), 1478 msg.arg1 != 0); 1479 d.show(); 1480 proc.anrDialog = d; 1481 } else { 1482 // Just kill the app if there is no dialog to be shown. 1483 killAppAtUsersRequest(proc, null); 1484 } 1485 } 1486 1487 ensureBootCompleted(); 1488 } break; 1489 case SHOW_STRICT_MODE_VIOLATION_MSG: { 1490 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj; 1491 synchronized (ActivityManagerService.this) { 1492 ProcessRecord proc = (ProcessRecord) data.get("app"); 1493 if (proc == null) { 1494 Slog.e(TAG, "App not found when showing strict mode dialog."); 1495 break; 1496 } 1497 if (proc.crashDialog != null) { 1498 Slog.e(TAG, "App already has strict mode dialog: " + proc); 1499 return; 1500 } 1501 AppErrorResult res = (AppErrorResult) data.get("result"); 1502 if (mShowDialogs && !mSleeping && !mShuttingDown) { 1503 Dialog d = new StrictModeViolationDialog(mContext, 1504 ActivityManagerService.this, res, proc); 1505 d.show(); 1506 proc.crashDialog = d; 1507 } else { 1508 // The device is asleep, so just pretend that the user 1509 // saw a crash dialog and hit "force quit". 1510 res.set(0); 1511 } 1512 } 1513 ensureBootCompleted(); 1514 } break; 1515 case SHOW_FACTORY_ERROR_MSG: { 1516 Dialog d = new FactoryErrorDialog( 1517 mContext, msg.getData().getCharSequence("msg")); 1518 d.show(); 1519 ensureBootCompleted(); 1520 } break; 1521 case WAIT_FOR_DEBUGGER_MSG: { 1522 synchronized (ActivityManagerService.this) { 1523 ProcessRecord app = (ProcessRecord)msg.obj; 1524 if (msg.arg1 != 0) { 1525 if (!app.waitedForDebugger) { 1526 Dialog d = new AppWaitingForDebuggerDialog( 1527 ActivityManagerService.this, 1528 mContext, app); 1529 app.waitDialog = d; 1530 app.waitedForDebugger = true; 1531 d.show(); 1532 } 1533 } else { 1534 if (app.waitDialog != null) { 1535 app.waitDialog.dismiss(); 1536 app.waitDialog = null; 1537 } 1538 } 1539 } 1540 } break; 1541 case SHOW_UID_ERROR_MSG: { 1542 if (mShowDialogs) { 1543 AlertDialog d = new BaseErrorDialog(mContext); 1544 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1545 d.setCancelable(false); 1546 d.setTitle(mContext.getText(R.string.android_system_label)); 1547 d.setMessage(mContext.getText(R.string.system_error_wipe_data)); 1548 d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok), 1549 obtainMessage(DISMISS_DIALOG_MSG, d)); 1550 d.show(); 1551 } 1552 } break; 1553 case SHOW_FINGERPRINT_ERROR_MSG: { 1554 if (mShowDialogs) { 1555 AlertDialog d = new BaseErrorDialog(mContext); 1556 d.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ERROR); 1557 d.setCancelable(false); 1558 d.setTitle(mContext.getText(R.string.android_system_label)); 1559 d.setMessage(mContext.getText(R.string.system_error_manufacturer)); 1560 d.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.ok), 1561 obtainMessage(DISMISS_DIALOG_MSG, d)); 1562 d.show(); 1563 } 1564 } break; 1565 case SHOW_COMPAT_MODE_DIALOG_MSG: { 1566 synchronized (ActivityManagerService.this) { 1567 ActivityRecord ar = (ActivityRecord) msg.obj; 1568 if (mCompatModeDialog != null) { 1569 if (mCompatModeDialog.mAppInfo.packageName.equals( 1570 ar.info.applicationInfo.packageName)) { 1571 return; 1572 } 1573 mCompatModeDialog.dismiss(); 1574 mCompatModeDialog = null; 1575 } 1576 if (ar != null && false) { 1577 if (mCompatModePackages.getPackageAskCompatModeLocked( 1578 ar.packageName)) { 1579 int mode = mCompatModePackages.computeCompatModeLocked( 1580 ar.info.applicationInfo); 1581 if (mode == ActivityManager.COMPAT_MODE_DISABLED 1582 || mode == ActivityManager.COMPAT_MODE_ENABLED) { 1583 mCompatModeDialog = new CompatModeDialog( 1584 ActivityManagerService.this, mContext, 1585 ar.info.applicationInfo); 1586 mCompatModeDialog.show(); 1587 } 1588 } 1589 } 1590 } 1591 break; 1592 } 1593 case START_USER_SWITCH_MSG: { 1594 showUserSwitchDialog(msg.arg1, (String) msg.obj); 1595 break; 1596 } 1597 case DISMISS_DIALOG_MSG: { 1598 final Dialog d = (Dialog) msg.obj; 1599 d.dismiss(); 1600 break; 1601 } 1602 case DISPATCH_PROCESSES_CHANGED: { 1603 dispatchProcessesChanged(); 1604 break; 1605 } 1606 case DISPATCH_PROCESS_DIED: { 1607 final int pid = msg.arg1; 1608 final int uid = msg.arg2; 1609 dispatchProcessDied(pid, uid); 1610 break; 1611 } 1612 case DISPATCH_UIDS_CHANGED_MSG: { 1613 dispatchUidsChanged(); 1614 } break; 1615 } 1616 } 1617 } 1618 1619 final class MainHandler extends Handler { MainHandler(Looper looper)1620 public MainHandler(Looper looper) { 1621 super(looper, null, true); 1622 } 1623 1624 @Override handleMessage(Message msg)1625 public void handleMessage(Message msg) { 1626 switch (msg.what) { 1627 case UPDATE_CONFIGURATION_MSG: { 1628 final ContentResolver resolver = mContext.getContentResolver(); 1629 Settings.System.putConfiguration(resolver, (Configuration) msg.obj); 1630 } break; 1631 case GC_BACKGROUND_PROCESSES_MSG: { 1632 synchronized (ActivityManagerService.this) { 1633 performAppGcsIfAppropriateLocked(); 1634 } 1635 } break; 1636 case SERVICE_TIMEOUT_MSG: { 1637 if (mDidDexOpt) { 1638 mDidDexOpt = false; 1639 Message nmsg = mHandler.obtainMessage(SERVICE_TIMEOUT_MSG); 1640 nmsg.obj = msg.obj; 1641 mHandler.sendMessageDelayed(nmsg, ActiveServices.SERVICE_TIMEOUT); 1642 return; 1643 } 1644 mServices.serviceTimeout((ProcessRecord)msg.obj); 1645 } break; 1646 case UPDATE_TIME_ZONE: { 1647 synchronized (ActivityManagerService.this) { 1648 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1649 ProcessRecord r = mLruProcesses.get(i); 1650 if (r.thread != null) { 1651 try { 1652 r.thread.updateTimeZone(); 1653 } catch (RemoteException ex) { 1654 Slog.w(TAG, "Failed to update time zone for: " + r.info.processName); 1655 } 1656 } 1657 } 1658 } 1659 } break; 1660 case CLEAR_DNS_CACHE_MSG: { 1661 synchronized (ActivityManagerService.this) { 1662 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1663 ProcessRecord r = mLruProcesses.get(i); 1664 if (r.thread != null) { 1665 try { 1666 r.thread.clearDnsCache(); 1667 } catch (RemoteException ex) { 1668 Slog.w(TAG, "Failed to clear dns cache for: " + r.info.processName); 1669 } 1670 } 1671 } 1672 } 1673 } break; 1674 case UPDATE_HTTP_PROXY_MSG: { 1675 ProxyInfo proxy = (ProxyInfo)msg.obj; 1676 String host = ""; 1677 String port = ""; 1678 String exclList = ""; 1679 Uri pacFileUrl = Uri.EMPTY; 1680 if (proxy != null) { 1681 host = proxy.getHost(); 1682 port = Integer.toString(proxy.getPort()); 1683 exclList = proxy.getExclusionListAsString(); 1684 pacFileUrl = proxy.getPacFileUrl(); 1685 } 1686 synchronized (ActivityManagerService.this) { 1687 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1688 ProcessRecord r = mLruProcesses.get(i); 1689 if (r.thread != null) { 1690 try { 1691 r.thread.setHttpProxy(host, port, exclList, pacFileUrl); 1692 } catch (RemoteException ex) { 1693 Slog.w(TAG, "Failed to update http proxy for: " + 1694 r.info.processName); 1695 } 1696 } 1697 } 1698 } 1699 } break; 1700 case PROC_START_TIMEOUT_MSG: { 1701 if (mDidDexOpt) { 1702 mDidDexOpt = false; 1703 Message nmsg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 1704 nmsg.obj = msg.obj; 1705 mHandler.sendMessageDelayed(nmsg, PROC_START_TIMEOUT); 1706 return; 1707 } 1708 ProcessRecord app = (ProcessRecord)msg.obj; 1709 synchronized (ActivityManagerService.this) { 1710 processStartTimedOutLocked(app); 1711 } 1712 } break; 1713 case CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG: { 1714 ProcessRecord app = (ProcessRecord)msg.obj; 1715 synchronized (ActivityManagerService.this) { 1716 processContentProviderPublishTimedOutLocked(app); 1717 } 1718 } break; 1719 case DO_PENDING_ACTIVITY_LAUNCHES_MSG: { 1720 synchronized (ActivityManagerService.this) { 1721 mStackSupervisor.doPendingActivityLaunchesLocked(true); 1722 } 1723 } break; 1724 case KILL_APPLICATION_MSG: { 1725 synchronized (ActivityManagerService.this) { 1726 int appid = msg.arg1; 1727 boolean restart = (msg.arg2 == 1); 1728 Bundle bundle = (Bundle)msg.obj; 1729 String pkg = bundle.getString("pkg"); 1730 String reason = bundle.getString("reason"); 1731 forceStopPackageLocked(pkg, appid, restart, false, true, false, 1732 false, UserHandle.USER_ALL, reason); 1733 } 1734 } break; 1735 case FINALIZE_PENDING_INTENT_MSG: { 1736 ((PendingIntentRecord)msg.obj).completeFinalize(); 1737 } break; 1738 case POST_HEAVY_NOTIFICATION_MSG: { 1739 INotificationManager inm = NotificationManager.getService(); 1740 if (inm == null) { 1741 return; 1742 } 1743 1744 ActivityRecord root = (ActivityRecord)msg.obj; 1745 ProcessRecord process = root.app; 1746 if (process == null) { 1747 return; 1748 } 1749 1750 try { 1751 Context context = mContext.createPackageContext(process.info.packageName, 0); 1752 String text = mContext.getString(R.string.heavy_weight_notification, 1753 context.getApplicationInfo().loadLabel(context.getPackageManager())); 1754 Notification notification = new Notification.Builder(context) 1755 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 1756 .setWhen(0) 1757 .setOngoing(true) 1758 .setTicker(text) 1759 .setColor(mContext.getColor( 1760 com.android.internal.R.color.system_notification_accent_color)) 1761 .setContentTitle(text) 1762 .setContentText( 1763 mContext.getText(R.string.heavy_weight_notification_detail)) 1764 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, 1765 root.intent, PendingIntent.FLAG_CANCEL_CURRENT, null, 1766 new UserHandle(root.userId))) 1767 .build(); 1768 try { 1769 int[] outId = new int[1]; 1770 inm.enqueueNotificationWithTag("android", "android", null, 1771 R.string.heavy_weight_notification, 1772 notification, outId, root.userId); 1773 } catch (RuntimeException e) { 1774 Slog.w(ActivityManagerService.TAG, 1775 "Error showing notification for heavy-weight app", e); 1776 } catch (RemoteException e) { 1777 } 1778 } catch (NameNotFoundException e) { 1779 Slog.w(TAG, "Unable to create context for heavy notification", e); 1780 } 1781 } break; 1782 case CANCEL_HEAVY_NOTIFICATION_MSG: { 1783 INotificationManager inm = NotificationManager.getService(); 1784 if (inm == null) { 1785 return; 1786 } 1787 try { 1788 inm.cancelNotificationWithTag("android", null, 1789 R.string.heavy_weight_notification, msg.arg1); 1790 } catch (RuntimeException e) { 1791 Slog.w(ActivityManagerService.TAG, 1792 "Error canceling notification for service", e); 1793 } catch (RemoteException e) { 1794 } 1795 } break; 1796 case CHECK_EXCESSIVE_WAKE_LOCKS_MSG: { 1797 synchronized (ActivityManagerService.this) { 1798 checkExcessivePowerUsageLocked(true); 1799 removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1800 Message nmsg = obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 1801 sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 1802 } 1803 } break; 1804 case REPORT_MEM_USAGE_MSG: { 1805 final ArrayList<ProcessMemInfo> memInfos = (ArrayList<ProcessMemInfo>)msg.obj; 1806 Thread thread = new Thread() { 1807 @Override public void run() { 1808 reportMemUsage(memInfos); 1809 } 1810 }; 1811 thread.start(); 1812 break; 1813 } 1814 case REPORT_USER_SWITCH_MSG: { 1815 dispatchUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 1816 break; 1817 } 1818 case CONTINUE_USER_SWITCH_MSG: { 1819 continueUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 1820 break; 1821 } 1822 case USER_SWITCH_TIMEOUT_MSG: { 1823 timeoutUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2); 1824 break; 1825 } 1826 case IMMERSIVE_MODE_LOCK_MSG: { 1827 final boolean nextState = (msg.arg1 != 0); 1828 if (mUpdateLock.isHeld() != nextState) { 1829 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, 1830 "Applying new update lock state '" + nextState 1831 + "' for " + (ActivityRecord)msg.obj); 1832 if (nextState) { 1833 mUpdateLock.acquire(); 1834 } else { 1835 mUpdateLock.release(); 1836 } 1837 } 1838 break; 1839 } 1840 case PERSIST_URI_GRANTS_MSG: { 1841 writeGrantedUriPermissions(); 1842 break; 1843 } 1844 case REQUEST_ALL_PSS_MSG: { 1845 synchronized (ActivityManagerService.this) { 1846 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, false); 1847 } 1848 break; 1849 } 1850 case START_PROFILES_MSG: { 1851 synchronized (ActivityManagerService.this) { 1852 startProfilesLocked(); 1853 } 1854 break; 1855 } 1856 case UPDATE_TIME: { 1857 synchronized (ActivityManagerService.this) { 1858 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 1859 ProcessRecord r = mLruProcesses.get(i); 1860 if (r.thread != null) { 1861 try { 1862 r.thread.updateTimePrefs(msg.arg1 == 0 ? false : true); 1863 } catch (RemoteException ex) { 1864 Slog.w(TAG, "Failed to update preferences for: " + r.info.processName); 1865 } 1866 } 1867 } 1868 } 1869 break; 1870 } 1871 case SYSTEM_USER_START_MSG: { 1872 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 1873 Integer.toString(msg.arg1), msg.arg1); 1874 mSystemServiceManager.startUser(msg.arg1); 1875 break; 1876 } 1877 case SYSTEM_USER_CURRENT_MSG: { 1878 mBatteryStatsService.noteEvent( 1879 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH, 1880 Integer.toString(msg.arg2), msg.arg2); 1881 mBatteryStatsService.noteEvent( 1882 BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 1883 Integer.toString(msg.arg1), msg.arg1); 1884 mSystemServiceManager.switchUser(msg.arg1); 1885 break; 1886 } 1887 case ENTER_ANIMATION_COMPLETE_MSG: { 1888 synchronized (ActivityManagerService.this) { 1889 ActivityRecord r = ActivityRecord.forTokenLocked((IBinder) msg.obj); 1890 if (r != null && r.app != null && r.app.thread != null) { 1891 try { 1892 r.app.thread.scheduleEnterAnimationComplete(r.appToken); 1893 } catch (RemoteException e) { 1894 } 1895 } 1896 } 1897 break; 1898 } 1899 case FINISH_BOOTING_MSG: { 1900 if (msg.arg1 != 0) { 1901 finishBooting(); 1902 } 1903 if (msg.arg2 != 0) { 1904 enableScreenAfterBoot(); 1905 } 1906 break; 1907 } 1908 case SEND_LOCALE_TO_MOUNT_DAEMON_MSG: { 1909 try { 1910 Locale l = (Locale) msg.obj; 1911 IBinder service = ServiceManager.getService("mount"); 1912 IMountService mountService = IMountService.Stub.asInterface(service); 1913 Log.d(TAG, "Storing locale " + l.toLanguageTag() + " for decryption UI"); 1914 mountService.setField(StorageManager.SYSTEM_LOCALE_KEY, l.toLanguageTag()); 1915 } catch (RemoteException e) { 1916 Log.e(TAG, "Error storing locale for decryption UI", e); 1917 } 1918 break; 1919 } 1920 case NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG: { 1921 synchronized (ActivityManagerService.this) { 1922 int i = mTaskStackListeners.beginBroadcast(); 1923 while (i > 0) { 1924 i--; 1925 try { 1926 // Make a one-way callback to the listener 1927 mTaskStackListeners.getBroadcastItem(i).onTaskStackChanged(); 1928 } catch (RemoteException e){ 1929 // Handled by the RemoteCallbackList 1930 } 1931 } 1932 mTaskStackListeners.finishBroadcast(); 1933 } 1934 break; 1935 } 1936 case NOTIFY_CLEARTEXT_NETWORK_MSG: { 1937 final int uid = msg.arg1; 1938 final byte[] firstPacket = (byte[]) msg.obj; 1939 1940 synchronized (mPidsSelfLocked) { 1941 for (int i = 0; i < mPidsSelfLocked.size(); i++) { 1942 final ProcessRecord p = mPidsSelfLocked.valueAt(i); 1943 if (p.uid == uid) { 1944 try { 1945 p.thread.notifyCleartextNetwork(firstPacket); 1946 } catch (RemoteException ignored) { 1947 } 1948 } 1949 } 1950 } 1951 break; 1952 } 1953 case POST_DUMP_HEAP_NOTIFICATION_MSG: { 1954 final String procName; 1955 final int uid; 1956 final long memLimit; 1957 final String reportPackage; 1958 synchronized (ActivityManagerService.this) { 1959 procName = mMemWatchDumpProcName; 1960 uid = mMemWatchDumpUid; 1961 Pair<Long, String> val = mMemWatchProcesses.get(procName, uid); 1962 if (val == null) { 1963 val = mMemWatchProcesses.get(procName, 0); 1964 } 1965 if (val != null) { 1966 memLimit = val.first; 1967 reportPackage = val.second; 1968 } else { 1969 memLimit = 0; 1970 reportPackage = null; 1971 } 1972 } 1973 if (procName == null) { 1974 return; 1975 } 1976 1977 if (DEBUG_PSS) Slog.d(TAG_PSS, 1978 "Showing dump heap notification from " + procName + "/" + uid); 1979 1980 INotificationManager inm = NotificationManager.getService(); 1981 if (inm == null) { 1982 return; 1983 } 1984 1985 String text = mContext.getString(R.string.dump_heap_notification, procName); 1986 1987 1988 Intent deleteIntent = new Intent(); 1989 deleteIntent.setAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP); 1990 Intent intent = new Intent(); 1991 intent.setClassName("android", DumpHeapActivity.class.getName()); 1992 intent.putExtra(DumpHeapActivity.KEY_PROCESS, procName); 1993 intent.putExtra(DumpHeapActivity.KEY_SIZE, memLimit); 1994 if (reportPackage != null) { 1995 intent.putExtra(DumpHeapActivity.KEY_DIRECT_LAUNCH, reportPackage); 1996 } 1997 int userId = UserHandle.getUserId(uid); 1998 Notification notification = new Notification.Builder(mContext) 1999 .setSmallIcon(com.android.internal.R.drawable.stat_sys_adb) 2000 .setWhen(0) 2001 .setOngoing(true) 2002 .setAutoCancel(true) 2003 .setTicker(text) 2004 .setColor(mContext.getColor( 2005 com.android.internal.R.color.system_notification_accent_color)) 2006 .setContentTitle(text) 2007 .setContentText( 2008 mContext.getText(R.string.dump_heap_notification_detail)) 2009 .setContentIntent(PendingIntent.getActivityAsUser(mContext, 0, 2010 intent, PendingIntent.FLAG_CANCEL_CURRENT, null, 2011 new UserHandle(userId))) 2012 .setDeleteIntent(PendingIntent.getBroadcastAsUser(mContext, 0, 2013 deleteIntent, 0, UserHandle.OWNER)) 2014 .build(); 2015 2016 try { 2017 int[] outId = new int[1]; 2018 inm.enqueueNotificationWithTag("android", "android", null, 2019 R.string.dump_heap_notification, 2020 notification, outId, userId); 2021 } catch (RuntimeException e) { 2022 Slog.w(ActivityManagerService.TAG, 2023 "Error showing notification for dump heap", e); 2024 } catch (RemoteException e) { 2025 } 2026 } break; 2027 case DELETE_DUMPHEAP_MSG: { 2028 revokeUriPermission(ActivityThread.currentActivityThread().getApplicationThread(), 2029 DumpHeapActivity.JAVA_URI, 2030 Intent.FLAG_GRANT_READ_URI_PERMISSION 2031 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 2032 UserHandle.myUserId()); 2033 synchronized (ActivityManagerService.this) { 2034 mMemWatchDumpFile = null; 2035 mMemWatchDumpProcName = null; 2036 mMemWatchDumpPid = -1; 2037 mMemWatchDumpUid = -1; 2038 } 2039 } break; 2040 case FOREGROUND_PROFILE_CHANGED_MSG: { 2041 dispatchForegroundProfileChanged(msg.arg1); 2042 } break; 2043 case REPORT_TIME_TRACKER_MSG: { 2044 AppTimeTracker tracker = (AppTimeTracker)msg.obj; 2045 tracker.deliverResult(mContext); 2046 } break; 2047 case REPORT_USER_SWITCH_COMPLETE_MSG: { 2048 dispatchUserSwitchComplete(msg.arg1); 2049 } break; 2050 case SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG: { 2051 IUiAutomationConnection connection = (IUiAutomationConnection) msg.obj; 2052 try { 2053 connection.shutdown(); 2054 } catch (RemoteException e) { 2055 Slog.w(TAG, "Error shutting down UiAutomationConnection"); 2056 } 2057 // Only a UiAutomation can set this flag and now that 2058 // it is finished we make sure it is reset to its default. 2059 mUserIsMonkey = false; 2060 } break; 2061 case APP_BOOST_DEACTIVATE_MSG : { 2062 synchronized(ActivityManagerService.this) { 2063 if (mIsBoosted) { 2064 if (mBoostStartTime < (SystemClock.uptimeMillis() - APP_BOOST_TIMEOUT)) { 2065 nativeMigrateFromBoost(); 2066 mIsBoosted = false; 2067 mBoostStartTime = 0; 2068 } else { 2069 Message newmsg = mHandler.obtainMessage(APP_BOOST_DEACTIVATE_MSG); 2070 mHandler.sendMessageDelayed(newmsg, APP_BOOST_TIMEOUT); 2071 } 2072 } 2073 } 2074 } break; 2075 } 2076 } 2077 }; 2078 2079 static final int COLLECT_PSS_BG_MSG = 1; 2080 2081 final Handler mBgHandler = new Handler(BackgroundThread.getHandler().getLooper()) { 2082 @Override 2083 public void handleMessage(Message msg) { 2084 switch (msg.what) { 2085 case COLLECT_PSS_BG_MSG: { 2086 long start = SystemClock.uptimeMillis(); 2087 MemInfoReader memInfo = null; 2088 synchronized (ActivityManagerService.this) { 2089 if (mFullPssPending) { 2090 mFullPssPending = false; 2091 memInfo = new MemInfoReader(); 2092 } 2093 } 2094 if (memInfo != null) { 2095 updateCpuStatsNow(); 2096 long nativeTotalPss = 0; 2097 synchronized (mProcessCpuTracker) { 2098 final int N = mProcessCpuTracker.countStats(); 2099 for (int j=0; j<N; j++) { 2100 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(j); 2101 if (st.vsize <= 0 || st.uid >= Process.FIRST_APPLICATION_UID) { 2102 // This is definitely an application process; skip it. 2103 continue; 2104 } 2105 synchronized (mPidsSelfLocked) { 2106 if (mPidsSelfLocked.indexOfKey(st.pid) >= 0) { 2107 // This is one of our own processes; skip it. 2108 continue; 2109 } 2110 } 2111 nativeTotalPss += Debug.getPss(st.pid, null, null); 2112 } 2113 } 2114 memInfo.readMemInfo(); 2115 synchronized (ActivityManagerService.this) { 2116 if (DEBUG_PSS) Slog.d(TAG_PSS, "Collected native and kernel memory in " 2117 + (SystemClock.uptimeMillis()-start) + "ms"); 2118 final long cachedKb = memInfo.getCachedSizeKb(); 2119 final long freeKb = memInfo.getFreeSizeKb(); 2120 final long zramKb = memInfo.getZramTotalSizeKb(); 2121 final long kernelKb = memInfo.getKernelUsedSizeKb(); 2122 EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024, 2123 kernelKb*1024, nativeTotalPss*1024); 2124 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 2125 nativeTotalPss); 2126 } 2127 } 2128 2129 int num = 0; 2130 long[] tmp = new long[1]; 2131 do { 2132 ProcessRecord proc; 2133 int procState; 2134 int pid; 2135 long lastPssTime; 2136 synchronized (ActivityManagerService.this) { 2137 if (mPendingPssProcesses.size() <= 0) { 2138 if (mTestPssMode || DEBUG_PSS) Slog.d(TAG_PSS, 2139 "Collected PSS of " + num + " processes in " 2140 + (SystemClock.uptimeMillis() - start) + "ms"); 2141 mPendingPssProcesses.clear(); 2142 return; 2143 } 2144 proc = mPendingPssProcesses.remove(0); 2145 procState = proc.pssProcState; 2146 lastPssTime = proc.lastPssTime; 2147 if (proc.thread != null && procState == proc.setProcState 2148 && (lastPssTime+ProcessList.PSS_SAFE_TIME_FROM_STATE_CHANGE) 2149 < SystemClock.uptimeMillis()) { 2150 pid = proc.pid; 2151 } else { 2152 proc = null; 2153 pid = 0; 2154 } 2155 } 2156 if (proc != null) { 2157 long pss = Debug.getPss(pid, tmp, null); 2158 synchronized (ActivityManagerService.this) { 2159 if (pss != 0 && proc.thread != null && proc.setProcState == procState 2160 && proc.pid == pid && proc.lastPssTime == lastPssTime) { 2161 num++; 2162 recordPssSampleLocked(proc, procState, pss, tmp[0], 2163 SystemClock.uptimeMillis()); 2164 } 2165 } 2166 } 2167 } while (true); 2168 } 2169 } 2170 } 2171 }; 2172 setSystemProcess()2173 public void setSystemProcess() { 2174 try { 2175 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true); 2176 ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats); 2177 ServiceManager.addService("meminfo", new MemBinder(this)); 2178 ServiceManager.addService("gfxinfo", new GraphicsBinder(this)); 2179 ServiceManager.addService("dbinfo", new DbBinder(this)); 2180 if (MONITOR_CPU_USAGE) { 2181 ServiceManager.addService("cpuinfo", new CpuBinder(this)); 2182 } 2183 ServiceManager.addService("permission", new PermissionController(this)); 2184 ServiceManager.addService("processinfo", new ProcessInfoService(this)); 2185 2186 ApplicationInfo info = mContext.getPackageManager().getApplicationInfo( 2187 "android", STOCK_PM_FLAGS); 2188 mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader()); 2189 2190 synchronized (this) { 2191 ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0); 2192 app.persistent = true; 2193 app.pid = MY_PID; 2194 app.maxAdj = ProcessList.SYSTEM_ADJ; 2195 app.makeActive(mSystemThread.getApplicationThread(), mProcessStats); 2196 synchronized (mPidsSelfLocked) { 2197 mPidsSelfLocked.put(app.pid, app); 2198 } 2199 updateLruProcessLocked(app, false, null); 2200 updateOomAdjLocked(); 2201 } 2202 } catch (PackageManager.NameNotFoundException e) { 2203 throw new RuntimeException( 2204 "Unable to find android system package", e); 2205 } 2206 } 2207 setWindowManager(WindowManagerService wm)2208 public void setWindowManager(WindowManagerService wm) { 2209 mWindowManager = wm; 2210 mStackSupervisor.setWindowManager(wm); 2211 } 2212 setUsageStatsManager(UsageStatsManagerInternal usageStatsManager)2213 public void setUsageStatsManager(UsageStatsManagerInternal usageStatsManager) { 2214 mUsageStatsService = usageStatsManager; 2215 } 2216 startObservingNativeCrashes()2217 public void startObservingNativeCrashes() { 2218 final NativeCrashListener ncl = new NativeCrashListener(this); 2219 ncl.start(); 2220 } 2221 getAppOpsService()2222 public IAppOpsService getAppOpsService() { 2223 return mAppOpsService; 2224 } 2225 2226 static class MemBinder extends Binder { 2227 ActivityManagerService mActivityManagerService; MemBinder(ActivityManagerService activityManagerService)2228 MemBinder(ActivityManagerService activityManagerService) { 2229 mActivityManagerService = activityManagerService; 2230 } 2231 2232 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2233 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2234 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2235 != PackageManager.PERMISSION_GRANTED) { 2236 pw.println("Permission Denial: can't dump meminfo from from pid=" 2237 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2238 + " without permission " + android.Manifest.permission.DUMP); 2239 return; 2240 } 2241 2242 mActivityManagerService.dumpApplicationMemoryUsage(fd, pw, " ", args, false, null); 2243 } 2244 } 2245 2246 static class GraphicsBinder extends Binder { 2247 ActivityManagerService mActivityManagerService; GraphicsBinder(ActivityManagerService activityManagerService)2248 GraphicsBinder(ActivityManagerService activityManagerService) { 2249 mActivityManagerService = activityManagerService; 2250 } 2251 2252 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2253 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2254 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2255 != PackageManager.PERMISSION_GRANTED) { 2256 pw.println("Permission Denial: can't dump gfxinfo from from pid=" 2257 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2258 + " without permission " + android.Manifest.permission.DUMP); 2259 return; 2260 } 2261 2262 mActivityManagerService.dumpGraphicsHardwareUsage(fd, pw, args); 2263 } 2264 } 2265 2266 static class DbBinder extends Binder { 2267 ActivityManagerService mActivityManagerService; DbBinder(ActivityManagerService activityManagerService)2268 DbBinder(ActivityManagerService activityManagerService) { 2269 mActivityManagerService = activityManagerService; 2270 } 2271 2272 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2273 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2274 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2275 != PackageManager.PERMISSION_GRANTED) { 2276 pw.println("Permission Denial: can't dump dbinfo from from pid=" 2277 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2278 + " without permission " + android.Manifest.permission.DUMP); 2279 return; 2280 } 2281 2282 mActivityManagerService.dumpDbInfo(fd, pw, args); 2283 } 2284 } 2285 2286 static class CpuBinder extends Binder { 2287 ActivityManagerService mActivityManagerService; CpuBinder(ActivityManagerService activityManagerService)2288 CpuBinder(ActivityManagerService activityManagerService) { 2289 mActivityManagerService = activityManagerService; 2290 } 2291 2292 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)2293 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 2294 if (mActivityManagerService.checkCallingPermission(android.Manifest.permission.DUMP) 2295 != PackageManager.PERMISSION_GRANTED) { 2296 pw.println("Permission Denial: can't dump cpuinfo from from pid=" 2297 + Binder.getCallingPid() + ", uid=" + Binder.getCallingUid() 2298 + " without permission " + android.Manifest.permission.DUMP); 2299 return; 2300 } 2301 2302 synchronized (mActivityManagerService.mProcessCpuTracker) { 2303 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentLoad()); 2304 pw.print(mActivityManagerService.mProcessCpuTracker.printCurrentState( 2305 SystemClock.uptimeMillis())); 2306 } 2307 } 2308 } 2309 2310 public static final class Lifecycle extends SystemService { 2311 private final ActivityManagerService mService; 2312 Lifecycle(Context context)2313 public Lifecycle(Context context) { 2314 super(context); 2315 mService = new ActivityManagerService(context); 2316 } 2317 2318 @Override onStart()2319 public void onStart() { 2320 mService.start(); 2321 } 2322 getService()2323 public ActivityManagerService getService() { 2324 return mService; 2325 } 2326 } 2327 2328 // Note: This method is invoked on the main thread but may need to attach various 2329 // handlers to other threads. So take care to be explicit about the looper. ActivityManagerService(Context systemContext)2330 public ActivityManagerService(Context systemContext) { 2331 mContext = systemContext; 2332 mFactoryTest = FactoryTest.getMode(); 2333 mSystemThread = ActivityThread.currentActivityThread(); 2334 2335 Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass()); 2336 2337 mHandlerThread = new ServiceThread(TAG, 2338 android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 2339 mHandlerThread.start(); 2340 mHandler = new MainHandler(mHandlerThread.getLooper()); 2341 mUiHandler = new UiHandler(); 2342 2343 mFgBroadcastQueue = new BroadcastQueue(this, mHandler, 2344 "foreground", BROADCAST_FG_TIMEOUT, false); 2345 mBgBroadcastQueue = new BroadcastQueue(this, mHandler, 2346 "background", BROADCAST_BG_TIMEOUT, true); 2347 mBroadcastQueues[0] = mFgBroadcastQueue; 2348 mBroadcastQueues[1] = mBgBroadcastQueue; 2349 2350 mServices = new ActiveServices(this); 2351 mProviderMap = new ProviderMap(this); 2352 2353 // TODO: Move creation of battery stats service outside of activity manager service. 2354 File dataDir = Environment.getDataDirectory(); 2355 File systemDir = new File(dataDir, "system"); 2356 systemDir.mkdirs(); 2357 mBatteryStatsService = new BatteryStatsService(systemDir, mHandler); 2358 mBatteryStatsService.getActiveStatistics().readLocked(); 2359 mBatteryStatsService.scheduleWriteToDisk(); 2360 mOnBattery = DEBUG_POWER ? true 2361 : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 2362 mBatteryStatsService.getActiveStatistics().setCallback(this); 2363 2364 mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats")); 2365 2366 mAppOpsService = new AppOpsService(new File(systemDir, "appops.xml"), mHandler); 2367 2368 mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml")); 2369 2370 // User 0 is the first and only user that runs at boot. 2371 mStartedUsers.put(UserHandle.USER_OWNER, new UserState(UserHandle.OWNER, true)); 2372 mUserLru.add(UserHandle.USER_OWNER); 2373 updateStartedUserArrayLocked(); 2374 2375 GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", 2376 ConfigurationInfo.GL_ES_VERSION_UNDEFINED); 2377 2378 mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations")); 2379 2380 mConfiguration.setToDefaults(); 2381 mConfiguration.setLocale(Locale.getDefault()); 2382 2383 mConfigurationSeq = mConfiguration.seq = 1; 2384 mProcessCpuTracker.init(); 2385 2386 mCompatModePackages = new CompatModePackages(this, systemDir, mHandler); 2387 mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler); 2388 mRecentTasks = new RecentTasks(this); 2389 mStackSupervisor = new ActivityStackSupervisor(this, mRecentTasks); 2390 mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, mRecentTasks); 2391 2392 mProcessCpuThread = new Thread("CpuTracker") { 2393 @Override 2394 public void run() { 2395 while (true) { 2396 try { 2397 try { 2398 synchronized(this) { 2399 final long now = SystemClock.uptimeMillis(); 2400 long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now; 2401 long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now; 2402 //Slog.i(TAG, "Cpu delay=" + nextCpuDelay 2403 // + ", write delay=" + nextWriteDelay); 2404 if (nextWriteDelay < nextCpuDelay) { 2405 nextCpuDelay = nextWriteDelay; 2406 } 2407 if (nextCpuDelay > 0) { 2408 mProcessCpuMutexFree.set(true); 2409 this.wait(nextCpuDelay); 2410 } 2411 } 2412 } catch (InterruptedException e) { 2413 } 2414 updateCpuStatsNow(); 2415 } catch (Exception e) { 2416 Slog.e(TAG, "Unexpected exception collecting process stats", e); 2417 } 2418 } 2419 } 2420 }; 2421 2422 Watchdog.getInstance().addMonitor(this); 2423 Watchdog.getInstance().addThread(mHandler); 2424 } 2425 setSystemServiceManager(SystemServiceManager mgr)2426 public void setSystemServiceManager(SystemServiceManager mgr) { 2427 mSystemServiceManager = mgr; 2428 } 2429 setInstaller(Installer installer)2430 public void setInstaller(Installer installer) { 2431 mInstaller = installer; 2432 } 2433 start()2434 private void start() { 2435 Process.removeAllProcessGroups(); 2436 mProcessCpuThread.start(); 2437 2438 mBatteryStatsService.publish(mContext); 2439 mAppOpsService.publish(mContext); 2440 Slog.d("AppOps", "AppOpsService published"); 2441 LocalServices.addService(ActivityManagerInternal.class, new LocalService()); 2442 } 2443 initPowerManagement()2444 public void initPowerManagement() { 2445 mStackSupervisor.initPowerManagement(); 2446 mBatteryStatsService.initPowerManagement(); 2447 mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class); 2448 PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE); 2449 mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*"); 2450 mVoiceWakeLock.setReferenceCounted(false); 2451 } 2452 2453 @Override onTransact(int code, Parcel data, Parcel reply, int flags)2454 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2455 throws RemoteException { 2456 if (code == SYSPROPS_TRANSACTION) { 2457 // We need to tell all apps about the system property change. 2458 ArrayList<IBinder> procs = new ArrayList<IBinder>(); 2459 synchronized(this) { 2460 final int NP = mProcessNames.getMap().size(); 2461 for (int ip=0; ip<NP; ip++) { 2462 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 2463 final int NA = apps.size(); 2464 for (int ia=0; ia<NA; ia++) { 2465 ProcessRecord app = apps.valueAt(ia); 2466 if (app.thread != null) { 2467 procs.add(app.thread.asBinder()); 2468 } 2469 } 2470 } 2471 } 2472 2473 int N = procs.size(); 2474 for (int i=0; i<N; i++) { 2475 Parcel data2 = Parcel.obtain(); 2476 try { 2477 procs.get(i).transact(IBinder.SYSPROPS_TRANSACTION, data2, null, 0); 2478 } catch (RemoteException e) { 2479 } 2480 data2.recycle(); 2481 } 2482 } 2483 try { 2484 return super.onTransact(code, data, reply, flags); 2485 } catch (RuntimeException e) { 2486 // The activity manager only throws security exceptions, so let's 2487 // log all others. 2488 if (!(e instanceof SecurityException)) { 2489 Slog.wtf(TAG, "Activity Manager Crash", e); 2490 } 2491 throw e; 2492 } 2493 } 2494 updateCpuStats()2495 void updateCpuStats() { 2496 final long now = SystemClock.uptimeMillis(); 2497 if (mLastCpuTime.get() >= now - MONITOR_CPU_MIN_TIME) { 2498 return; 2499 } 2500 if (mProcessCpuMutexFree.compareAndSet(true, false)) { 2501 synchronized (mProcessCpuThread) { 2502 mProcessCpuThread.notify(); 2503 } 2504 } 2505 } 2506 updateCpuStatsNow()2507 void updateCpuStatsNow() { 2508 synchronized (mProcessCpuTracker) { 2509 mProcessCpuMutexFree.set(false); 2510 final long now = SystemClock.uptimeMillis(); 2511 boolean haveNewCpuStats = false; 2512 2513 if (MONITOR_CPU_USAGE && 2514 mLastCpuTime.get() < (now-MONITOR_CPU_MIN_TIME)) { 2515 mLastCpuTime.set(now); 2516 mProcessCpuTracker.update(); 2517 if (mProcessCpuTracker.hasGoodLastStats()) { 2518 haveNewCpuStats = true; 2519 //Slog.i(TAG, mProcessCpu.printCurrentState()); 2520 //Slog.i(TAG, "Total CPU usage: " 2521 // + mProcessCpu.getTotalCpuPercent() + "%"); 2522 2523 // Slog the cpu usage if the property is set. 2524 if ("true".equals(SystemProperties.get("events.cpu"))) { 2525 int user = mProcessCpuTracker.getLastUserTime(); 2526 int system = mProcessCpuTracker.getLastSystemTime(); 2527 int iowait = mProcessCpuTracker.getLastIoWaitTime(); 2528 int irq = mProcessCpuTracker.getLastIrqTime(); 2529 int softIrq = mProcessCpuTracker.getLastSoftIrqTime(); 2530 int idle = mProcessCpuTracker.getLastIdleTime(); 2531 2532 int total = user + system + iowait + irq + softIrq + idle; 2533 if (total == 0) total = 1; 2534 2535 EventLog.writeEvent(EventLogTags.CPU, 2536 ((user+system+iowait+irq+softIrq) * 100) / total, 2537 (user * 100) / total, 2538 (system * 100) / total, 2539 (iowait * 100) / total, 2540 (irq * 100) / total, 2541 (softIrq * 100) / total); 2542 } 2543 } 2544 } 2545 2546 final BatteryStatsImpl bstats = mBatteryStatsService.getActiveStatistics(); 2547 synchronized(bstats) { 2548 synchronized(mPidsSelfLocked) { 2549 if (haveNewCpuStats) { 2550 if (bstats.startAddingCpuLocked()) { 2551 int totalUTime = 0; 2552 int totalSTime = 0; 2553 final int N = mProcessCpuTracker.countStats(); 2554 for (int i=0; i<N; i++) { 2555 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 2556 if (!st.working) { 2557 continue; 2558 } 2559 ProcessRecord pr = mPidsSelfLocked.get(st.pid); 2560 totalUTime += st.rel_utime; 2561 totalSTime += st.rel_stime; 2562 if (pr != null) { 2563 BatteryStatsImpl.Uid.Proc ps = pr.curProcBatteryStats; 2564 if (ps == null || !ps.isActive()) { 2565 pr.curProcBatteryStats = ps = bstats.getProcessStatsLocked( 2566 pr.info.uid, pr.processName); 2567 } 2568 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime); 2569 pr.curCpuTime += st.rel_utime + st.rel_stime; 2570 } else { 2571 BatteryStatsImpl.Uid.Proc ps = st.batteryStats; 2572 if (ps == null || !ps.isActive()) { 2573 st.batteryStats = ps = bstats.getProcessStatsLocked( 2574 bstats.mapUid(st.uid), st.name); 2575 } 2576 ps.addCpuTimeLocked(st.rel_utime, st.rel_stime); 2577 } 2578 } 2579 final int userTime = mProcessCpuTracker.getLastUserTime(); 2580 final int systemTime = mProcessCpuTracker.getLastSystemTime(); 2581 final int iowaitTime = mProcessCpuTracker.getLastIoWaitTime(); 2582 final int irqTime = mProcessCpuTracker.getLastIrqTime(); 2583 final int softIrqTime = mProcessCpuTracker.getLastSoftIrqTime(); 2584 final int idleTime = mProcessCpuTracker.getLastIdleTime(); 2585 bstats.finishAddingCpuLocked(totalUTime, totalSTime, userTime, 2586 systemTime, iowaitTime, irqTime, softIrqTime, idleTime); 2587 } 2588 } 2589 } 2590 2591 if (mLastWriteTime < (now-BATTERY_STATS_TIME)) { 2592 mLastWriteTime = now; 2593 mBatteryStatsService.scheduleWriteToDisk(); 2594 } 2595 } 2596 } 2597 } 2598 2599 @Override batteryNeedsCpuUpdate()2600 public void batteryNeedsCpuUpdate() { 2601 updateCpuStatsNow(); 2602 } 2603 2604 @Override batteryPowerChanged(boolean onBattery)2605 public void batteryPowerChanged(boolean onBattery) { 2606 // When plugging in, update the CPU stats first before changing 2607 // the plug state. 2608 updateCpuStatsNow(); 2609 synchronized (this) { 2610 synchronized(mPidsSelfLocked) { 2611 mOnBattery = DEBUG_POWER ? true : onBattery; 2612 } 2613 } 2614 } 2615 2616 @Override batterySendBroadcast(Intent intent)2617 public void batterySendBroadcast(Intent intent) { 2618 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 2619 AppOpsManager.OP_NONE, null, false, false, 2620 -1, Process.SYSTEM_UID, UserHandle.USER_ALL); 2621 } 2622 2623 /** 2624 * Initialize the application bind args. These are passed to each 2625 * process when the bindApplication() IPC is sent to the process. They're 2626 * lazily setup to make sure the services are running when they're asked for. 2627 */ getCommonServicesLocked(boolean isolated)2628 private HashMap<String, IBinder> getCommonServicesLocked(boolean isolated) { 2629 if (mAppBindArgs == null) { 2630 mAppBindArgs = new HashMap<>(); 2631 2632 // Isolated processes won't get this optimization, so that we don't 2633 // violate the rules about which services they have access to. 2634 if (!isolated) { 2635 // Setup the application init args 2636 mAppBindArgs.put("package", ServiceManager.getService("package")); 2637 mAppBindArgs.put("window", ServiceManager.getService("window")); 2638 mAppBindArgs.put(Context.ALARM_SERVICE, 2639 ServiceManager.getService(Context.ALARM_SERVICE)); 2640 } 2641 } 2642 return mAppBindArgs; 2643 } 2644 setFocusedActivityLocked(ActivityRecord r, String reason)2645 final void setFocusedActivityLocked(ActivityRecord r, String reason) { 2646 if (r != null && mFocusedActivity != r) { 2647 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedActivityLocked: r=" + r); 2648 ActivityRecord last = mFocusedActivity; 2649 mFocusedActivity = r; 2650 if (r.task.taskType != ActivityRecord.HOME_ACTIVITY_TYPE 2651 && r.task.taskType != ActivityRecord.RECENTS_ACTIVITY_TYPE) { 2652 if (mCurAppTimeTracker != r.appTimeTracker) { 2653 // We are switching app tracking. Complete the current one. 2654 if (mCurAppTimeTracker != null) { 2655 mCurAppTimeTracker.stop(); 2656 mHandler.obtainMessage(REPORT_TIME_TRACKER_MSG, 2657 mCurAppTimeTracker).sendToTarget(); 2658 mStackSupervisor.clearOtherAppTimeTrackers(r.appTimeTracker); 2659 mCurAppTimeTracker = null; 2660 } 2661 if (r.appTimeTracker != null) { 2662 mCurAppTimeTracker = r.appTimeTracker; 2663 startTimeTrackingFocusedActivityLocked(); 2664 } 2665 } else { 2666 startTimeTrackingFocusedActivityLocked(); 2667 } 2668 } else { 2669 r.appTimeTracker = null; 2670 } 2671 if (r.task != null && r.task.voiceInteractor != null) { 2672 startRunningVoiceLocked(r.task.voiceSession, r.info.applicationInfo.uid); 2673 } else { 2674 finishRunningVoiceLocked(); 2675 if (last != null && last.task.voiceSession != null) { 2676 // We had been in a voice interaction session, but now focused has 2677 // move to something different. Just finish the session, we can't 2678 // return to it and retain the proper state and synchronization with 2679 // the voice interaction service. 2680 finishVoiceTask(last.task.voiceSession); 2681 } 2682 } 2683 if (mStackSupervisor.setFocusedStack(r, reason + " setFocusedActivity")) { 2684 mWindowManager.setFocusedApp(r.appToken, true); 2685 } 2686 applyUpdateLockStateLocked(r); 2687 if (mFocusedActivity.userId != mLastFocusedUserId) { 2688 mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG); 2689 mHandler.sendMessage(mHandler.obtainMessage(FOREGROUND_PROFILE_CHANGED_MSG, 2690 mFocusedActivity.userId, 0)); 2691 mLastFocusedUserId = mFocusedActivity.userId; 2692 } 2693 } 2694 EventLog.writeEvent(EventLogTags.AM_FOCUSED_ACTIVITY, 2695 mFocusedActivity == null ? -1 : mFocusedActivity.userId, 2696 mFocusedActivity == null ? "NULL" : mFocusedActivity.shortComponentName); 2697 } 2698 clearFocusedActivity(ActivityRecord r)2699 final void clearFocusedActivity(ActivityRecord r) { 2700 if (mFocusedActivity == r) { 2701 ActivityStack stack = mStackSupervisor.getFocusedStack(); 2702 if (stack != null) { 2703 ActivityRecord top = stack.topActivity(); 2704 if (top != null && top.userId != mLastFocusedUserId) { 2705 mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG); 2706 mHandler.sendMessage(mHandler.obtainMessage(FOREGROUND_PROFILE_CHANGED_MSG, 2707 top.userId, 0)); 2708 mLastFocusedUserId = top.userId; 2709 } 2710 } 2711 mFocusedActivity = null; 2712 EventLog.writeEvent(EventLogTags.AM_FOCUSED_ACTIVITY, -1, "NULL"); 2713 } 2714 } 2715 2716 @Override setFocusedStack(int stackId)2717 public void setFocusedStack(int stackId) { 2718 if (DEBUG_FOCUS) Slog.d(TAG_FOCUS, "setFocusedStack: stackId=" + stackId); 2719 synchronized (ActivityManagerService.this) { 2720 ActivityStack stack = mStackSupervisor.getStack(stackId); 2721 if (stack != null) { 2722 ActivityRecord r = stack.topRunningActivityLocked(null); 2723 if (r != null) { 2724 setFocusedActivityLocked(r, "setFocusedStack"); 2725 mStackSupervisor.resumeTopActivitiesLocked(stack, null, null); 2726 } 2727 } 2728 } 2729 } 2730 2731 /** Sets the task stack listener that gets callbacks when a task stack changes. */ 2732 @Override registerTaskStackListener(ITaskStackListener listener)2733 public void registerTaskStackListener(ITaskStackListener listener) throws RemoteException { 2734 synchronized (ActivityManagerService.this) { 2735 if (listener != null) { 2736 mTaskStackListeners.register(listener); 2737 } 2738 } 2739 } 2740 2741 @Override notifyActivityDrawn(IBinder token)2742 public void notifyActivityDrawn(IBinder token) { 2743 if (DEBUG_VISIBILITY) Slog.d(TAG_VISIBILITY, "notifyActivityDrawn: token=" + token); 2744 synchronized (this) { 2745 ActivityRecord r = mStackSupervisor.isInAnyStackLocked(token); 2746 if (r != null) { 2747 r.task.stack.notifyActivityDrawnLocked(r); 2748 } 2749 } 2750 } 2751 applyUpdateLockStateLocked(ActivityRecord r)2752 final void applyUpdateLockStateLocked(ActivityRecord r) { 2753 // Modifications to the UpdateLock state are done on our handler, outside 2754 // the activity manager's locks. The new state is determined based on the 2755 // state *now* of the relevant activity record. The object is passed to 2756 // the handler solely for logging detail, not to be consulted/modified. 2757 final boolean nextState = r != null && r.immersive; 2758 mHandler.sendMessage( 2759 mHandler.obtainMessage(IMMERSIVE_MODE_LOCK_MSG, (nextState) ? 1 : 0, 0, r)); 2760 } 2761 showAskCompatModeDialogLocked(ActivityRecord r)2762 final void showAskCompatModeDialogLocked(ActivityRecord r) { 2763 Message msg = Message.obtain(); 2764 msg.what = SHOW_COMPAT_MODE_DIALOG_MSG; 2765 msg.obj = r.task.askedCompatMode ? null : r; 2766 mUiHandler.sendMessage(msg); 2767 } 2768 updateLruProcessInternalLocked(ProcessRecord app, long now, int index, String what, Object obj, ProcessRecord srcApp)2769 private int updateLruProcessInternalLocked(ProcessRecord app, long now, int index, 2770 String what, Object obj, ProcessRecord srcApp) { 2771 app.lastActivityTime = now; 2772 2773 if (app.activities.size() > 0) { 2774 // Don't want to touch dependent processes that are hosting activities. 2775 return index; 2776 } 2777 2778 int lrui = mLruProcesses.lastIndexOf(app); 2779 if (lrui < 0) { 2780 Slog.wtf(TAG, "Adding dependent process " + app + " not on LRU list: " 2781 + what + " " + obj + " from " + srcApp); 2782 return index; 2783 } 2784 2785 if (lrui >= index) { 2786 // Don't want to cause this to move dependent processes *back* in the 2787 // list as if they were less frequently used. 2788 return index; 2789 } 2790 2791 if (lrui >= mLruProcessActivityStart) { 2792 // Don't want to touch dependent processes that are hosting activities. 2793 return index; 2794 } 2795 2796 mLruProcesses.remove(lrui); 2797 if (index > 0) { 2798 index--; 2799 } 2800 if (DEBUG_LRU) Slog.d(TAG_LRU, "Moving dep from " + lrui + " to " + index 2801 + " in LRU list: " + app); 2802 mLruProcesses.add(index, app); 2803 return index; 2804 } 2805 killProcessGroup(int uid, int pid)2806 private static void killProcessGroup(int uid, int pid) { 2807 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "killProcessGroup"); 2808 Process.killProcessGroup(uid, pid); 2809 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 2810 } 2811 removeLruProcessLocked(ProcessRecord app)2812 final void removeLruProcessLocked(ProcessRecord app) { 2813 int lrui = mLruProcesses.lastIndexOf(app); 2814 if (lrui >= 0) { 2815 if (!app.killed) { 2816 Slog.wtfStack(TAG, "Removing process that hasn't been killed: " + app); 2817 Process.killProcessQuiet(app.pid); 2818 killProcessGroup(app.uid, app.pid); 2819 } 2820 if (lrui <= mLruProcessActivityStart) { 2821 mLruProcessActivityStart--; 2822 } 2823 if (lrui <= mLruProcessServiceStart) { 2824 mLruProcessServiceStart--; 2825 } 2826 mLruProcesses.remove(lrui); 2827 } 2828 } 2829 updateLruProcessLocked(ProcessRecord app, boolean activityChange, ProcessRecord client)2830 final void updateLruProcessLocked(ProcessRecord app, boolean activityChange, 2831 ProcessRecord client) { 2832 final boolean hasActivity = app.activities.size() > 0 || app.hasClientActivities 2833 || app.treatLikeActivity; 2834 final boolean hasService = false; // not impl yet. app.services.size() > 0; 2835 if (!activityChange && hasActivity) { 2836 // The process has activities, so we are only allowing activity-based adjustments 2837 // to move it. It should be kept in the front of the list with other 2838 // processes that have activities, and we don't want those to change their 2839 // order except due to activity operations. 2840 return; 2841 } 2842 2843 mLruSeq++; 2844 final long now = SystemClock.uptimeMillis(); 2845 app.lastActivityTime = now; 2846 2847 // First a quick reject: if the app is already at the position we will 2848 // put it, then there is nothing to do. 2849 if (hasActivity) { 2850 final int N = mLruProcesses.size(); 2851 if (N > 0 && mLruProcesses.get(N-1) == app) { 2852 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top activity: " + app); 2853 return; 2854 } 2855 } else { 2856 if (mLruProcessServiceStart > 0 2857 && mLruProcesses.get(mLruProcessServiceStart-1) == app) { 2858 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, already top other: " + app); 2859 return; 2860 } 2861 } 2862 2863 int lrui = mLruProcesses.lastIndexOf(app); 2864 2865 if (app.persistent && lrui >= 0) { 2866 // We don't care about the position of persistent processes, as long as 2867 // they are in the list. 2868 if (DEBUG_LRU) Slog.d(TAG_LRU, "Not moving, persistent: " + app); 2869 return; 2870 } 2871 2872 /* In progress: compute new position first, so we can avoid doing work 2873 if the process is not actually going to move. Not yet working. 2874 int addIndex; 2875 int nextIndex; 2876 boolean inActivity = false, inService = false; 2877 if (hasActivity) { 2878 // Process has activities, put it at the very tipsy-top. 2879 addIndex = mLruProcesses.size(); 2880 nextIndex = mLruProcessServiceStart; 2881 inActivity = true; 2882 } else if (hasService) { 2883 // Process has services, put it at the top of the service list. 2884 addIndex = mLruProcessActivityStart; 2885 nextIndex = mLruProcessServiceStart; 2886 inActivity = true; 2887 inService = true; 2888 } else { 2889 // Process not otherwise of interest, it goes to the top of the non-service area. 2890 addIndex = mLruProcessServiceStart; 2891 if (client != null) { 2892 int clientIndex = mLruProcesses.lastIndexOf(client); 2893 if (clientIndex < 0) Slog.d(TAG, "Unknown client " + client + " when updating " 2894 + app); 2895 if (clientIndex >= 0 && addIndex > clientIndex) { 2896 addIndex = clientIndex; 2897 } 2898 } 2899 nextIndex = addIndex > 0 ? addIndex-1 : addIndex; 2900 } 2901 2902 Slog.d(TAG, "Update LRU at " + lrui + " to " + addIndex + " (act=" 2903 + mLruProcessActivityStart + "): " + app); 2904 */ 2905 2906 if (lrui >= 0) { 2907 if (lrui < mLruProcessActivityStart) { 2908 mLruProcessActivityStart--; 2909 } 2910 if (lrui < mLruProcessServiceStart) { 2911 mLruProcessServiceStart--; 2912 } 2913 /* 2914 if (addIndex > lrui) { 2915 addIndex--; 2916 } 2917 if (nextIndex > lrui) { 2918 nextIndex--; 2919 } 2920 */ 2921 mLruProcesses.remove(lrui); 2922 } 2923 2924 /* 2925 mLruProcesses.add(addIndex, app); 2926 if (inActivity) { 2927 mLruProcessActivityStart++; 2928 } 2929 if (inService) { 2930 mLruProcessActivityStart++; 2931 } 2932 */ 2933 2934 int nextIndex; 2935 if (hasActivity) { 2936 final int N = mLruProcesses.size(); 2937 if (app.activities.size() == 0 && mLruProcessActivityStart < (N - 1)) { 2938 // Process doesn't have activities, but has clients with 2939 // activities... move it up, but one below the top (the top 2940 // should always have a real activity). 2941 if (DEBUG_LRU) Slog.d(TAG_LRU, 2942 "Adding to second-top of LRU activity list: " + app); 2943 mLruProcesses.add(N - 1, app); 2944 // To keep it from spamming the LRU list (by making a bunch of clients), 2945 // we will push down any other entries owned by the app. 2946 final int uid = app.info.uid; 2947 for (int i = N - 2; i > mLruProcessActivityStart; i--) { 2948 ProcessRecord subProc = mLruProcesses.get(i); 2949 if (subProc.info.uid == uid) { 2950 // We want to push this one down the list. If the process after 2951 // it is for the same uid, however, don't do so, because we don't 2952 // want them internally to be re-ordered. 2953 if (mLruProcesses.get(i - 1).info.uid != uid) { 2954 if (DEBUG_LRU) Slog.d(TAG_LRU, 2955 "Pushing uid " + uid + " swapping at " + i + ": " 2956 + mLruProcesses.get(i) + " : " + mLruProcesses.get(i - 1)); 2957 ProcessRecord tmp = mLruProcesses.get(i); 2958 mLruProcesses.set(i, mLruProcesses.get(i - 1)); 2959 mLruProcesses.set(i - 1, tmp); 2960 i--; 2961 } 2962 } else { 2963 // A gap, we can stop here. 2964 break; 2965 } 2966 } 2967 } else { 2968 // Process has activities, put it at the very tipsy-top. 2969 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU activity list: " + app); 2970 mLruProcesses.add(app); 2971 } 2972 nextIndex = mLruProcessServiceStart; 2973 } else if (hasService) { 2974 // Process has services, put it at the top of the service list. 2975 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding to top of LRU service list: " + app); 2976 mLruProcesses.add(mLruProcessActivityStart, app); 2977 nextIndex = mLruProcessServiceStart; 2978 mLruProcessActivityStart++; 2979 } else { 2980 // Process not otherwise of interest, it goes to the top of the non-service area. 2981 int index = mLruProcessServiceStart; 2982 if (client != null) { 2983 // If there is a client, don't allow the process to be moved up higher 2984 // in the list than that client. 2985 int clientIndex = mLruProcesses.lastIndexOf(client); 2986 if (DEBUG_LRU && clientIndex < 0) Slog.d(TAG_LRU, "Unknown client " + client 2987 + " when updating " + app); 2988 if (clientIndex <= lrui) { 2989 // Don't allow the client index restriction to push it down farther in the 2990 // list than it already is. 2991 clientIndex = lrui; 2992 } 2993 if (clientIndex >= 0 && index > clientIndex) { 2994 index = clientIndex; 2995 } 2996 } 2997 if (DEBUG_LRU) Slog.d(TAG_LRU, "Adding at " + index + " of LRU list: " + app); 2998 mLruProcesses.add(index, app); 2999 nextIndex = index-1; 3000 mLruProcessActivityStart++; 3001 mLruProcessServiceStart++; 3002 } 3003 3004 // If the app is currently using a content provider or service, 3005 // bump those processes as well. 3006 for (int j=app.connections.size()-1; j>=0; j--) { 3007 ConnectionRecord cr = app.connections.valueAt(j); 3008 if (cr.binding != null && !cr.serviceDead && cr.binding.service != null 3009 && cr.binding.service.app != null 3010 && cr.binding.service.app.lruSeq != mLruSeq 3011 && !cr.binding.service.app.persistent) { 3012 nextIndex = updateLruProcessInternalLocked(cr.binding.service.app, now, nextIndex, 3013 "service connection", cr, app); 3014 } 3015 } 3016 for (int j=app.conProviders.size()-1; j>=0; j--) { 3017 ContentProviderRecord cpr = app.conProviders.get(j).provider; 3018 if (cpr.proc != null && cpr.proc.lruSeq != mLruSeq && !cpr.proc.persistent) { 3019 nextIndex = updateLruProcessInternalLocked(cpr.proc, now, nextIndex, 3020 "provider reference", cpr, app); 3021 } 3022 } 3023 } 3024 getProcessRecordLocked(String processName, int uid, boolean keepIfLarge)3025 final ProcessRecord getProcessRecordLocked(String processName, int uid, boolean keepIfLarge) { 3026 if (uid == Process.SYSTEM_UID) { 3027 // The system gets to run in any process. If there are multiple 3028 // processes with the same uid, just pick the first (this 3029 // should never happen). 3030 SparseArray<ProcessRecord> procs = mProcessNames.getMap().get(processName); 3031 if (procs == null) return null; 3032 final int procCount = procs.size(); 3033 for (int i = 0; i < procCount; i++) { 3034 final int procUid = procs.keyAt(i); 3035 if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) { 3036 // Don't use an app process or different user process for system component. 3037 continue; 3038 } 3039 return procs.valueAt(i); 3040 } 3041 } 3042 ProcessRecord proc = mProcessNames.get(processName, uid); 3043 if (false && proc != null && !keepIfLarge 3044 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY 3045 && proc.lastCachedPss >= 4000) { 3046 // Turn this condition on to cause killing to happen regularly, for testing. 3047 if (proc.baseProcessTracker != null) { 3048 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 3049 } 3050 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 3051 } else if (proc != null && !keepIfLarge 3052 && mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 3053 && proc.setProcState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 3054 if (DEBUG_PSS) Slog.d(TAG_PSS, "May not keep " + proc + ": pss=" + proc.lastCachedPss); 3055 if (proc.lastCachedPss >= mProcessList.getCachedRestoreThresholdKb()) { 3056 if (proc.baseProcessTracker != null) { 3057 proc.baseProcessTracker.reportCachedKill(proc.pkgList, proc.lastCachedPss); 3058 } 3059 proc.kill(Long.toString(proc.lastCachedPss) + "k from cached", true); 3060 } 3061 } 3062 return proc; 3063 } 3064 ensurePackageDexOpt(String packageName)3065 void ensurePackageDexOpt(String packageName) { 3066 IPackageManager pm = AppGlobals.getPackageManager(); 3067 try { 3068 if (pm.performDexOptIfNeeded(packageName, null /* instruction set */)) { 3069 mDidDexOpt = true; 3070 } 3071 } catch (RemoteException e) { 3072 } 3073 } 3074 isNextTransitionForward()3075 boolean isNextTransitionForward() { 3076 int transit = mWindowManager.getPendingAppTransition(); 3077 return transit == AppTransition.TRANSIT_ACTIVITY_OPEN 3078 || transit == AppTransition.TRANSIT_TASK_OPEN 3079 || transit == AppTransition.TRANSIT_TASK_TO_FRONT; 3080 } 3081 startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)3082 int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 3083 String processName, String abiOverride, int uid, Runnable crashHandler) { 3084 synchronized(this) { 3085 ApplicationInfo info = new ApplicationInfo(); 3086 // In general the ApplicationInfo.uid isn't neccesarily equal to ProcessRecord.uid. 3087 // For isolated processes, the former contains the parent's uid and the latter the 3088 // actual uid of the isolated process. 3089 // In the special case introduced by this method (which is, starting an isolated 3090 // process directly from the SystemServer without an actual parent app process) the 3091 // closest thing to a parent's uid is SYSTEM_UID. 3092 // The only important thing here is to keep AI.uid != PR.uid, in order to trigger 3093 // the |isolated| logic in the ProcessRecord constructor. 3094 info.uid = Process.SYSTEM_UID; 3095 info.processName = processName; 3096 info.className = entryPoint; 3097 info.packageName = "android"; 3098 ProcessRecord proc = startProcessLocked(processName, info /* info */, 3099 false /* knownToBeDead */, 0 /* intentFlags */, "" /* hostingType */, 3100 null /* hostingName */, true /* allowWhileBooting */, true /* isolated */, 3101 uid, true /* keepIfLarge */, abiOverride, entryPoint, entryPointArgs, 3102 crashHandler); 3103 return proc != null ? proc.pid : 0; 3104 } 3105 } 3106 startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, boolean allowWhileBooting, boolean isolated, boolean keepIfLarge)3107 final ProcessRecord startProcessLocked(String processName, 3108 ApplicationInfo info, boolean knownToBeDead, int intentFlags, 3109 String hostingType, ComponentName hostingName, boolean allowWhileBooting, 3110 boolean isolated, boolean keepIfLarge) { 3111 return startProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType, 3112 hostingName, allowWhileBooting, isolated, 0 /* isolatedUid */, keepIfLarge, 3113 null /* ABI override */, null /* entryPoint */, null /* entryPointArgs */, 3114 null /* crashHandler */); 3115 } 3116 startProcessLocked(String processName, ApplicationInfo info, boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge, String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler)3117 final ProcessRecord startProcessLocked(String processName, ApplicationInfo info, 3118 boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName, 3119 boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge, 3120 String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) { 3121 long startTime = SystemClock.elapsedRealtime(); 3122 ProcessRecord app; 3123 if (!isolated) { 3124 app = getProcessRecordLocked(processName, info.uid, keepIfLarge); 3125 checkTime(startTime, "startProcess: after getProcessRecord"); 3126 3127 if ((intentFlags & Intent.FLAG_FROM_BACKGROUND) != 0) { 3128 // If we are in the background, then check to see if this process 3129 // is bad. If so, we will just silently fail. 3130 if (mBadProcesses.get(info.processName, info.uid) != null) { 3131 if (DEBUG_PROCESSES) Slog.v(TAG, "Bad process: " + info.uid 3132 + "/" + info.processName); 3133 return null; 3134 } 3135 } else { 3136 // When the user is explicitly starting a process, then clear its 3137 // crash count so that we won't make it bad until they see at 3138 // least one crash dialog again, and make the process good again 3139 // if it had been bad. 3140 if (DEBUG_PROCESSES) Slog.v(TAG, "Clearing bad process: " + info.uid 3141 + "/" + info.processName); 3142 mProcessCrashTimes.remove(info.processName, info.uid); 3143 if (mBadProcesses.get(info.processName, info.uid) != null) { 3144 EventLog.writeEvent(EventLogTags.AM_PROC_GOOD, 3145 UserHandle.getUserId(info.uid), info.uid, 3146 info.processName); 3147 mBadProcesses.remove(info.processName, info.uid); 3148 if (app != null) { 3149 app.bad = false; 3150 } 3151 } 3152 } 3153 } else { 3154 // If this is an isolated process, it can't re-use an existing process. 3155 app = null; 3156 } 3157 3158 // app launch boost for big.little configurations 3159 // use cpusets to migrate freshly launched tasks to big cores 3160 synchronized(ActivityManagerService.this) { 3161 nativeMigrateToBoost(); 3162 mIsBoosted = true; 3163 mBoostStartTime = SystemClock.uptimeMillis(); 3164 Message msg = mHandler.obtainMessage(APP_BOOST_DEACTIVATE_MSG); 3165 mHandler.sendMessageDelayed(msg, APP_BOOST_MESSAGE_DELAY); 3166 } 3167 3168 // We don't have to do anything more if: 3169 // (1) There is an existing application record; and 3170 // (2) The caller doesn't think it is dead, OR there is no thread 3171 // object attached to it so we know it couldn't have crashed; and 3172 // (3) There is a pid assigned to it, so it is either starting or 3173 // already running. 3174 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "startProcess: name=" + processName 3175 + " app=" + app + " knownToBeDead=" + knownToBeDead 3176 + " thread=" + (app != null ? app.thread : null) 3177 + " pid=" + (app != null ? app.pid : -1)); 3178 if (app != null && app.pid > 0) { 3179 if (!knownToBeDead || app.thread == null) { 3180 // We already have the app running, or are waiting for it to 3181 // come up (we have a pid but not yet its thread), so keep it. 3182 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "App already running: " + app); 3183 // If this is a new package in the process, add the package to the list 3184 app.addPackage(info.packageName, info.versionCode, mProcessStats); 3185 checkTime(startTime, "startProcess: done, added package to proc"); 3186 return app; 3187 } 3188 3189 // An application record is attached to a previous process, 3190 // clean it up now. 3191 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_PROCESSES, "App died: " + app); 3192 checkTime(startTime, "startProcess: bad proc running, killing"); 3193 killProcessGroup(app.uid, app.pid); 3194 handleAppDiedLocked(app, true, true); 3195 checkTime(startTime, "startProcess: done killing old proc"); 3196 } 3197 3198 String hostingNameStr = hostingName != null 3199 ? hostingName.flattenToShortString() : null; 3200 3201 if (app == null) { 3202 checkTime(startTime, "startProcess: creating new process record"); 3203 app = newProcessRecordLocked(info, processName, isolated, isolatedUid); 3204 if (app == null) { 3205 Slog.w(TAG, "Failed making new process record for " 3206 + processName + "/" + info.uid + " isolated=" + isolated); 3207 return null; 3208 } 3209 app.crashHandler = crashHandler; 3210 checkTime(startTime, "startProcess: done creating new process record"); 3211 } else { 3212 // If this is a new package in the process, add the package to the list 3213 app.addPackage(info.packageName, info.versionCode, mProcessStats); 3214 checkTime(startTime, "startProcess: added package to existing proc"); 3215 } 3216 3217 // If the system is not ready yet, then hold off on starting this 3218 // process until it is. 3219 if (!mProcessesReady 3220 && !isAllowedWhileBooting(info) 3221 && !allowWhileBooting) { 3222 if (!mProcessesOnHold.contains(app)) { 3223 mProcessesOnHold.add(app); 3224 } 3225 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, 3226 "System not ready, putting on hold: " + app); 3227 checkTime(startTime, "startProcess: returning with proc on hold"); 3228 return app; 3229 } 3230 3231 checkTime(startTime, "startProcess: stepping in to startProcess"); 3232 startProcessLocked( 3233 app, hostingType, hostingNameStr, abiOverride, entryPoint, entryPointArgs); 3234 checkTime(startTime, "startProcess: done starting proc!"); 3235 return (app.pid != 0) ? app : null; 3236 } 3237 isAllowedWhileBooting(ApplicationInfo ai)3238 boolean isAllowedWhileBooting(ApplicationInfo ai) { 3239 return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0; 3240 } 3241 startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr)3242 private final void startProcessLocked(ProcessRecord app, 3243 String hostingType, String hostingNameStr) { 3244 startProcessLocked(app, hostingType, hostingNameStr, null /* abiOverride */, 3245 null /* entryPoint */, null /* entryPointArgs */); 3246 } 3247 startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs)3248 private final void startProcessLocked(ProcessRecord app, String hostingType, 3249 String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) { 3250 long startTime = SystemClock.elapsedRealtime(); 3251 if (app.pid > 0 && app.pid != MY_PID) { 3252 checkTime(startTime, "startProcess: removing from pids map"); 3253 synchronized (mPidsSelfLocked) { 3254 mPidsSelfLocked.remove(app.pid); 3255 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 3256 } 3257 checkTime(startTime, "startProcess: done removing from pids map"); 3258 app.setPid(0); 3259 } 3260 3261 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, 3262 "startProcessLocked removing on hold: " + app); 3263 mProcessesOnHold.remove(app); 3264 3265 checkTime(startTime, "startProcess: starting to update cpu stats"); 3266 updateCpuStats(); 3267 checkTime(startTime, "startProcess: done updating cpu stats"); 3268 3269 try { 3270 try { 3271 if (AppGlobals.getPackageManager().isPackageFrozen(app.info.packageName)) { 3272 // This is caught below as if we had failed to fork zygote 3273 throw new RuntimeException("Package " + app.info.packageName + " is frozen!"); 3274 } 3275 } catch (RemoteException e) { 3276 throw e.rethrowAsRuntimeException(); 3277 } 3278 3279 int uid = app.uid; 3280 int[] gids = null; 3281 int mountExternal = Zygote.MOUNT_EXTERNAL_NONE; 3282 if (!app.isolated) { 3283 int[] permGids = null; 3284 try { 3285 checkTime(startTime, "startProcess: getting gids from package manager"); 3286 final IPackageManager pm = AppGlobals.getPackageManager(); 3287 permGids = pm.getPackageGids(app.info.packageName, app.userId); 3288 MountServiceInternal mountServiceInternal = LocalServices.getService( 3289 MountServiceInternal.class); 3290 mountExternal = mountServiceInternal.getExternalStorageMountMode(uid, 3291 app.info.packageName); 3292 } catch (RemoteException e) { 3293 throw e.rethrowAsRuntimeException(); 3294 } 3295 3296 /* 3297 * Add shared application and profile GIDs so applications can share some 3298 * resources like shared libraries and access user-wide resources 3299 */ 3300 if (ArrayUtils.isEmpty(permGids)) { 3301 gids = new int[2]; 3302 } else { 3303 gids = new int[permGids.length + 2]; 3304 System.arraycopy(permGids, 0, gids, 2, permGids.length); 3305 } 3306 gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid)); 3307 gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid)); 3308 } 3309 checkTime(startTime, "startProcess: building args"); 3310 if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) { 3311 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 3312 && mTopComponent != null 3313 && app.processName.equals(mTopComponent.getPackageName())) { 3314 uid = 0; 3315 } 3316 if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL 3317 && (app.info.flags&ApplicationInfo.FLAG_FACTORY_TEST) != 0) { 3318 uid = 0; 3319 } 3320 } 3321 int debugFlags = 0; 3322 if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 3323 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER; 3324 // Also turn on CheckJNI for debuggable apps. It's quite 3325 // awkward to turn on otherwise. 3326 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 3327 } 3328 // Run the app in safe mode if its manifest requests so or the 3329 // system is booted in safe mode. 3330 if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || 3331 mSafeMode == true) { 3332 debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE; 3333 } 3334 if ("1".equals(SystemProperties.get("debug.checkjni"))) { 3335 debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI; 3336 } 3337 String jitDebugProperty = SystemProperties.get("debug.usejit"); 3338 if ("true".equals(jitDebugProperty)) { 3339 debugFlags |= Zygote.DEBUG_ENABLE_JIT; 3340 } else if (!"false".equals(jitDebugProperty)) { 3341 // If we didn't force disable by setting false, defer to the dalvik vm options. 3342 if ("true".equals(SystemProperties.get("dalvik.vm.usejit"))) { 3343 debugFlags |= Zygote.DEBUG_ENABLE_JIT; 3344 } 3345 } 3346 String genDebugInfoProperty = SystemProperties.get("debug.generate-debug-info"); 3347 if ("true".equals(genDebugInfoProperty)) { 3348 debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO; 3349 } 3350 if ("1".equals(SystemProperties.get("debug.jni.logging"))) { 3351 debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING; 3352 } 3353 if ("1".equals(SystemProperties.get("debug.assert"))) { 3354 debugFlags |= Zygote.DEBUG_ENABLE_ASSERT; 3355 } 3356 3357 String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi; 3358 if (requiredAbi == null) { 3359 requiredAbi = Build.SUPPORTED_ABIS[0]; 3360 } 3361 3362 String instructionSet = null; 3363 if (app.info.primaryCpuAbi != null) { 3364 instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi); 3365 } 3366 3367 app.gids = gids; 3368 app.requiredAbi = requiredAbi; 3369 app.instructionSet = instructionSet; 3370 3371 // Start the process. It will either succeed and return a result containing 3372 // the PID of the new process, or else throw a RuntimeException. 3373 boolean isActivityProcess = (entryPoint == null); 3374 if (entryPoint == null) entryPoint = "android.app.ActivityThread"; 3375 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " + 3376 app.processName); 3377 checkTime(startTime, "startProcess: asking zygote to start proc"); 3378 Process.ProcessStartResult startResult = Process.start(entryPoint, 3379 app.processName, uid, uid, gids, debugFlags, mountExternal, 3380 app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet, 3381 app.info.dataDir, entryPointArgs); 3382 checkTime(startTime, "startProcess: returned from zygote!"); 3383 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); 3384 3385 if (app.isolated) { 3386 mBatteryStatsService.addIsolatedUid(app.uid, app.info.uid); 3387 } 3388 mBatteryStatsService.noteProcessStart(app.processName, app.info.uid); 3389 checkTime(startTime, "startProcess: done updating battery stats"); 3390 3391 EventLog.writeEvent(EventLogTags.AM_PROC_START, 3392 UserHandle.getUserId(uid), startResult.pid, uid, 3393 app.processName, hostingType, 3394 hostingNameStr != null ? hostingNameStr : ""); 3395 3396 if (app.persistent) { 3397 Watchdog.getInstance().processStarted(app.processName, startResult.pid); 3398 } 3399 3400 checkTime(startTime, "startProcess: building log message"); 3401 StringBuilder buf = mStringBuilder; 3402 buf.setLength(0); 3403 buf.append("Start proc "); 3404 buf.append(startResult.pid); 3405 buf.append(':'); 3406 buf.append(app.processName); 3407 buf.append('/'); 3408 UserHandle.formatUid(buf, uid); 3409 if (!isActivityProcess) { 3410 buf.append(" ["); 3411 buf.append(entryPoint); 3412 buf.append("]"); 3413 } 3414 buf.append(" for "); 3415 buf.append(hostingType); 3416 if (hostingNameStr != null) { 3417 buf.append(" "); 3418 buf.append(hostingNameStr); 3419 } 3420 Slog.i(TAG, buf.toString()); 3421 app.setPid(startResult.pid); 3422 app.usingWrapper = startResult.usingWrapper; 3423 app.removed = false; 3424 app.killed = false; 3425 app.killedByAm = false; 3426 checkTime(startTime, "startProcess: starting to update pids map"); 3427 synchronized (mPidsSelfLocked) { 3428 this.mPidsSelfLocked.put(startResult.pid, app); 3429 if (isActivityProcess) { 3430 Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG); 3431 msg.obj = app; 3432 mHandler.sendMessageDelayed(msg, startResult.usingWrapper 3433 ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT); 3434 } 3435 } 3436 checkTime(startTime, "startProcess: done updating pids map"); 3437 } catch (RuntimeException e) { 3438 // XXX do better error recovery. 3439 app.setPid(0); 3440 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 3441 if (app.isolated) { 3442 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 3443 } 3444 Slog.e(TAG, "Failure starting process " + app.processName, e); 3445 } 3446 } 3447 updateUsageStats(ActivityRecord component, boolean resumed)3448 void updateUsageStats(ActivityRecord component, boolean resumed) { 3449 if (DEBUG_SWITCH) Slog.d(TAG_SWITCH, 3450 "updateUsageStats: comp=" + component + "res=" + resumed); 3451 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 3452 if (resumed) { 3453 if (mUsageStatsService != null) { 3454 mUsageStatsService.reportEvent(component.realActivity, component.userId, 3455 UsageEvents.Event.MOVE_TO_FOREGROUND); 3456 } 3457 synchronized (stats) { 3458 stats.noteActivityResumedLocked(component.app.uid); 3459 } 3460 } else { 3461 if (mUsageStatsService != null) { 3462 mUsageStatsService.reportEvent(component.realActivity, component.userId, 3463 UsageEvents.Event.MOVE_TO_BACKGROUND); 3464 } 3465 synchronized (stats) { 3466 stats.noteActivityPausedLocked(component.app.uid); 3467 } 3468 } 3469 } 3470 getHomeIntent()3471 Intent getHomeIntent() { 3472 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null); 3473 intent.setComponent(mTopComponent); 3474 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 3475 intent.addCategory(Intent.CATEGORY_HOME); 3476 } 3477 return intent; 3478 } 3479 startHomeActivityLocked(int userId, String reason)3480 boolean startHomeActivityLocked(int userId, String reason) { 3481 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL 3482 && mTopAction == null) { 3483 // We are running in factory test mode, but unable to find 3484 // the factory test app, so just sit around displaying the 3485 // error message and don't try to start anything. 3486 return false; 3487 } 3488 Intent intent = getHomeIntent(); 3489 ActivityInfo aInfo = 3490 resolveActivityInfo(intent, STOCK_PM_FLAGS, userId); 3491 if (aInfo != null) { 3492 intent.setComponent(new ComponentName( 3493 aInfo.applicationInfo.packageName, aInfo.name)); 3494 // Don't do this if the home app is currently being 3495 // instrumented. 3496 aInfo = new ActivityInfo(aInfo); 3497 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId); 3498 ProcessRecord app = getProcessRecordLocked(aInfo.processName, 3499 aInfo.applicationInfo.uid, true); 3500 if (app == null || app.instrumentationClass == null) { 3501 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK); 3502 mStackSupervisor.startHomeActivity(intent, aInfo, reason); 3503 } 3504 } 3505 3506 return true; 3507 } 3508 resolveActivityInfo(Intent intent, int flags, int userId)3509 private ActivityInfo resolveActivityInfo(Intent intent, int flags, int userId) { 3510 ActivityInfo ai = null; 3511 ComponentName comp = intent.getComponent(); 3512 try { 3513 if (comp != null) { 3514 // Factory test. 3515 ai = AppGlobals.getPackageManager().getActivityInfo(comp, flags, userId); 3516 } else { 3517 ResolveInfo info = AppGlobals.getPackageManager().resolveIntent( 3518 intent, 3519 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 3520 flags, userId); 3521 3522 if (info != null) { 3523 ai = info.activityInfo; 3524 } 3525 } 3526 } catch (RemoteException e) { 3527 // ignore 3528 } 3529 3530 return ai; 3531 } 3532 3533 /** 3534 * Starts the "new version setup screen" if appropriate. 3535 */ startSetupActivityLocked()3536 void startSetupActivityLocked() { 3537 // Only do this once per boot. 3538 if (mCheckedForSetup) { 3539 return; 3540 } 3541 3542 // We will show this screen if the current one is a different 3543 // version than the last one shown, and we are not running in 3544 // low-level factory test mode. 3545 final ContentResolver resolver = mContext.getContentResolver(); 3546 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL && 3547 Settings.Global.getInt(resolver, 3548 Settings.Global.DEVICE_PROVISIONED, 0) != 0) { 3549 mCheckedForSetup = true; 3550 3551 // See if we should be showing the platform update setup UI. 3552 Intent intent = new Intent(Intent.ACTION_UPGRADE_SETUP); 3553 List<ResolveInfo> ris = mContext.getPackageManager() 3554 .queryIntentActivities(intent, PackageManager.GET_META_DATA); 3555 3556 // We don't allow third party apps to replace this. 3557 ResolveInfo ri = null; 3558 for (int i=0; ris != null && i<ris.size(); i++) { 3559 if ((ris.get(i).activityInfo.applicationInfo.flags 3560 & ApplicationInfo.FLAG_SYSTEM) != 0) { 3561 ri = ris.get(i); 3562 break; 3563 } 3564 } 3565 3566 if (ri != null) { 3567 String vers = ri.activityInfo.metaData != null 3568 ? ri.activityInfo.metaData.getString(Intent.METADATA_SETUP_VERSION) 3569 : null; 3570 if (vers == null && ri.activityInfo.applicationInfo.metaData != null) { 3571 vers = ri.activityInfo.applicationInfo.metaData.getString( 3572 Intent.METADATA_SETUP_VERSION); 3573 } 3574 String lastVers = Settings.Secure.getString( 3575 resolver, Settings.Secure.LAST_SETUP_SHOWN); 3576 if (vers != null && !vers.equals(lastVers)) { 3577 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 3578 intent.setComponent(new ComponentName( 3579 ri.activityInfo.packageName, ri.activityInfo.name)); 3580 mStackSupervisor.startActivityLocked(null, intent, null, ri.activityInfo, 3581 null, null, null, null, 0, 0, 0, null, 0, 0, 0, null, false, false, 3582 null, null, null); 3583 } 3584 } 3585 } 3586 } 3587 compatibilityInfoForPackageLocked(ApplicationInfo ai)3588 CompatibilityInfo compatibilityInfoForPackageLocked(ApplicationInfo ai) { 3589 return mCompatModePackages.compatibilityInfoForPackageLocked(ai); 3590 } 3591 enforceNotIsolatedCaller(String caller)3592 void enforceNotIsolatedCaller(String caller) { 3593 if (UserHandle.isIsolated(Binder.getCallingUid())) { 3594 throw new SecurityException("Isolated process not allowed to call " + caller); 3595 } 3596 } 3597 enforceShellRestriction(String restriction, int userHandle)3598 void enforceShellRestriction(String restriction, int userHandle) { 3599 if (Binder.getCallingUid() == Process.SHELL_UID) { 3600 if (userHandle < 0 3601 || mUserManager.hasUserRestriction(restriction, userHandle)) { 3602 throw new SecurityException("Shell does not have permission to access user " 3603 + userHandle); 3604 } 3605 } 3606 } 3607 3608 @Override getFrontActivityScreenCompatMode()3609 public int getFrontActivityScreenCompatMode() { 3610 enforceNotIsolatedCaller("getFrontActivityScreenCompatMode"); 3611 synchronized (this) { 3612 return mCompatModePackages.getFrontActivityScreenCompatModeLocked(); 3613 } 3614 } 3615 3616 @Override setFrontActivityScreenCompatMode(int mode)3617 public void setFrontActivityScreenCompatMode(int mode) { 3618 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3619 "setFrontActivityScreenCompatMode"); 3620 synchronized (this) { 3621 mCompatModePackages.setFrontActivityScreenCompatModeLocked(mode); 3622 } 3623 } 3624 3625 @Override getPackageScreenCompatMode(String packageName)3626 public int getPackageScreenCompatMode(String packageName) { 3627 enforceNotIsolatedCaller("getPackageScreenCompatMode"); 3628 synchronized (this) { 3629 return mCompatModePackages.getPackageScreenCompatModeLocked(packageName); 3630 } 3631 } 3632 3633 @Override setPackageScreenCompatMode(String packageName, int mode)3634 public void setPackageScreenCompatMode(String packageName, int mode) { 3635 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3636 "setPackageScreenCompatMode"); 3637 synchronized (this) { 3638 mCompatModePackages.setPackageScreenCompatModeLocked(packageName, mode); 3639 } 3640 } 3641 3642 @Override getPackageAskScreenCompat(String packageName)3643 public boolean getPackageAskScreenCompat(String packageName) { 3644 enforceNotIsolatedCaller("getPackageAskScreenCompat"); 3645 synchronized (this) { 3646 return mCompatModePackages.getPackageAskCompatModeLocked(packageName); 3647 } 3648 } 3649 3650 @Override setPackageAskScreenCompat(String packageName, boolean ask)3651 public void setPackageAskScreenCompat(String packageName, boolean ask) { 3652 enforceCallingPermission(android.Manifest.permission.SET_SCREEN_COMPATIBILITY, 3653 "setPackageAskScreenCompat"); 3654 synchronized (this) { 3655 mCompatModePackages.setPackageAskCompatModeLocked(packageName, ask); 3656 } 3657 } 3658 hasUsageStatsPermission(String callingPackage)3659 private boolean hasUsageStatsPermission(String callingPackage) { 3660 final int mode = mAppOpsService.checkOperation(AppOpsManager.OP_GET_USAGE_STATS, 3661 Binder.getCallingUid(), callingPackage); 3662 if (mode == AppOpsManager.MODE_DEFAULT) { 3663 return checkCallingPermission(Manifest.permission.PACKAGE_USAGE_STATS) 3664 == PackageManager.PERMISSION_GRANTED; 3665 } 3666 return mode == AppOpsManager.MODE_ALLOWED; 3667 } 3668 3669 @Override getPackageProcessState(String packageName, String callingPackage)3670 public int getPackageProcessState(String packageName, String callingPackage) { 3671 if (!hasUsageStatsPermission(callingPackage)) { 3672 enforceCallingPermission(android.Manifest.permission.GET_PACKAGE_IMPORTANCE, 3673 "getPackageProcessState"); 3674 } 3675 3676 int procState = ActivityManager.PROCESS_STATE_NONEXISTENT; 3677 synchronized (this) { 3678 for (int i=mLruProcesses.size()-1; i>=0; i--) { 3679 final ProcessRecord proc = mLruProcesses.get(i); 3680 if (procState == ActivityManager.PROCESS_STATE_NONEXISTENT 3681 || procState > proc.setProcState) { 3682 boolean found = false; 3683 for (int j=proc.pkgList.size()-1; j>=0 && !found; j--) { 3684 if (proc.pkgList.keyAt(j).equals(packageName)) { 3685 procState = proc.setProcState; 3686 found = true; 3687 } 3688 } 3689 if (proc.pkgDeps != null && !found) { 3690 for (int j=proc.pkgDeps.size()-1; j>=0; j--) { 3691 if (proc.pkgDeps.valueAt(j).equals(packageName)) { 3692 procState = proc.setProcState; 3693 break; 3694 } 3695 } 3696 } 3697 } 3698 } 3699 } 3700 return procState; 3701 } 3702 3703 @Override setProcessMemoryTrimLevel(String process, int userId, int level)3704 public boolean setProcessMemoryTrimLevel(String process, int userId, int level) { 3705 synchronized (this) { 3706 final ProcessRecord app = findProcessLocked(process, userId, "setProcessMemoryTrimLevel"); 3707 if (app == null) { 3708 return false; 3709 } 3710 if (app.trimMemoryLevel < level && app.thread != null && 3711 (level < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN || 3712 app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND)) { 3713 try { 3714 app.thread.scheduleTrimMemory(level); 3715 app.trimMemoryLevel = level; 3716 return true; 3717 } catch (RemoteException e) { 3718 // Fallthrough to failure case. 3719 } 3720 } 3721 } 3722 return false; 3723 } 3724 dispatchProcessesChanged()3725 private void dispatchProcessesChanged() { 3726 int N; 3727 synchronized (this) { 3728 N = mPendingProcessChanges.size(); 3729 if (mActiveProcessChanges.length < N) { 3730 mActiveProcessChanges = new ProcessChangeItem[N]; 3731 } 3732 mPendingProcessChanges.toArray(mActiveProcessChanges); 3733 mPendingProcessChanges.clear(); 3734 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3735 "*** Delivering " + N + " process changes"); 3736 } 3737 3738 int i = mProcessObservers.beginBroadcast(); 3739 while (i > 0) { 3740 i--; 3741 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 3742 if (observer != null) { 3743 try { 3744 for (int j=0; j<N; j++) { 3745 ProcessChangeItem item = mActiveProcessChanges[j]; 3746 if ((item.changes&ProcessChangeItem.CHANGE_ACTIVITIES) != 0) { 3747 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3748 "ACTIVITIES CHANGED pid=" + item.pid + " uid=" 3749 + item.uid + ": " + item.foregroundActivities); 3750 observer.onForegroundActivitiesChanged(item.pid, item.uid, 3751 item.foregroundActivities); 3752 } 3753 if ((item.changes&ProcessChangeItem.CHANGE_PROCESS_STATE) != 0) { 3754 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 3755 "PROCSTATE CHANGED pid=" + item.pid + " uid=" + item.uid 3756 + ": " + item.processState); 3757 observer.onProcessStateChanged(item.pid, item.uid, item.processState); 3758 } 3759 } 3760 } catch (RemoteException e) { 3761 } 3762 } 3763 } 3764 mProcessObservers.finishBroadcast(); 3765 3766 synchronized (this) { 3767 for (int j=0; j<N; j++) { 3768 mAvailProcessChanges.add(mActiveProcessChanges[j]); 3769 } 3770 } 3771 } 3772 dispatchProcessDied(int pid, int uid)3773 private void dispatchProcessDied(int pid, int uid) { 3774 int i = mProcessObservers.beginBroadcast(); 3775 while (i > 0) { 3776 i--; 3777 final IProcessObserver observer = mProcessObservers.getBroadcastItem(i); 3778 if (observer != null) { 3779 try { 3780 observer.onProcessDied(pid, uid); 3781 } catch (RemoteException e) { 3782 } 3783 } 3784 } 3785 mProcessObservers.finishBroadcast(); 3786 } 3787 dispatchUidsChanged()3788 private void dispatchUidsChanged() { 3789 int N; 3790 synchronized (this) { 3791 N = mPendingUidChanges.size(); 3792 if (mActiveUidChanges.length < N) { 3793 mActiveUidChanges = new UidRecord.ChangeItem[N]; 3794 } 3795 for (int i=0; i<N; i++) { 3796 final UidRecord.ChangeItem change = mPendingUidChanges.get(i); 3797 mActiveUidChanges[i] = change; 3798 change.uidRecord.pendingChange = null; 3799 change.uidRecord = null; 3800 } 3801 mPendingUidChanges.clear(); 3802 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3803 "*** Delivering " + N + " uid changes"); 3804 } 3805 3806 if (mLocalPowerManager != null) { 3807 for (int j=0; j<N; j++) { 3808 UidRecord.ChangeItem item = mActiveUidChanges[j]; 3809 if (item.gone) { 3810 mLocalPowerManager.uidGone(item.uid); 3811 } else { 3812 mLocalPowerManager.updateUidProcState(item.uid, item.processState); 3813 } 3814 } 3815 } 3816 3817 int i = mUidObservers.beginBroadcast(); 3818 while (i > 0) { 3819 i--; 3820 final IUidObserver observer = mUidObservers.getBroadcastItem(i); 3821 if (observer != null) { 3822 try { 3823 for (int j=0; j<N; j++) { 3824 UidRecord.ChangeItem item = mActiveUidChanges[j]; 3825 if (item.gone) { 3826 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3827 "UID gone uid=" + item.uid); 3828 observer.onUidGone(item.uid); 3829 } else { 3830 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 3831 "UID CHANGED uid=" + item.uid 3832 + ": " + item.processState); 3833 observer.onUidStateChanged(item.uid, item.processState); 3834 } 3835 } 3836 } catch (RemoteException e) { 3837 } 3838 } 3839 } 3840 mUidObservers.finishBroadcast(); 3841 3842 synchronized (this) { 3843 for (int j=0; j<N; j++) { 3844 mAvailUidChanges.add(mActiveUidChanges[j]); 3845 } 3846 } 3847 } 3848 3849 @Override startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options)3850 public final int startActivity(IApplicationThread caller, String callingPackage, 3851 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3852 int startFlags, ProfilerInfo profilerInfo, Bundle options) { 3853 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, 3854 resultWho, requestCode, startFlags, profilerInfo, options, 3855 UserHandle.getCallingUserId()); 3856 } 3857 3858 @Override startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId)3859 public final int startActivityAsUser(IApplicationThread caller, String callingPackage, 3860 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3861 int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) { 3862 enforceNotIsolatedCaller("startActivity"); 3863 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3864 false, ALLOW_FULL_ONLY, "startActivity", null); 3865 // TODO: Switch to user app stacks here. 3866 return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, 3867 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 3868 profilerInfo, null, null, options, false, userId, null, null); 3869 } 3870 3871 @Override startActivityAsCaller(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options, boolean ignoreTargetSecurity, int userId)3872 public final int startActivityAsCaller(IApplicationThread caller, String callingPackage, 3873 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3874 int startFlags, ProfilerInfo profilerInfo, Bundle options, boolean ignoreTargetSecurity, 3875 int userId) { 3876 3877 // This is very dangerous -- it allows you to perform a start activity (including 3878 // permission grants) as any app that may launch one of your own activities. So 3879 // we will only allow this to be done from activities that are part of the core framework, 3880 // and then only when they are running as the system. 3881 final ActivityRecord sourceRecord; 3882 final int targetUid; 3883 final String targetPackage; 3884 synchronized (this) { 3885 if (resultTo == null) { 3886 throw new SecurityException("Must be called from an activity"); 3887 } 3888 sourceRecord = mStackSupervisor.isInAnyStackLocked(resultTo); 3889 if (sourceRecord == null) { 3890 throw new SecurityException("Called with bad activity token: " + resultTo); 3891 } 3892 if (!sourceRecord.info.packageName.equals("android")) { 3893 throw new SecurityException( 3894 "Must be called from an activity that is declared in the android package"); 3895 } 3896 if (sourceRecord.app == null) { 3897 throw new SecurityException("Called without a process attached to activity"); 3898 } 3899 if (UserHandle.getAppId(sourceRecord.app.uid) != Process.SYSTEM_UID) { 3900 // This is still okay, as long as this activity is running under the 3901 // uid of the original calling activity. 3902 if (sourceRecord.app.uid != sourceRecord.launchedFromUid) { 3903 throw new SecurityException( 3904 "Calling activity in uid " + sourceRecord.app.uid 3905 + " must be system uid or original calling uid " 3906 + sourceRecord.launchedFromUid); 3907 } 3908 } 3909 if (ignoreTargetSecurity) { 3910 if (intent.getComponent() == null) { 3911 throw new SecurityException( 3912 "Component must be specified with ignoreTargetSecurity"); 3913 } 3914 if (intent.getSelector() != null) { 3915 throw new SecurityException( 3916 "Selector not allowed with ignoreTargetSecurity"); 3917 } 3918 } 3919 targetUid = sourceRecord.launchedFromUid; 3920 targetPackage = sourceRecord.launchedFromPackage; 3921 } 3922 3923 if (userId == UserHandle.USER_NULL) { 3924 userId = UserHandle.getUserId(sourceRecord.app.uid); 3925 } 3926 3927 // TODO: Switch to user app stacks here. 3928 try { 3929 int ret = mStackSupervisor.startActivityMayWait(null, targetUid, targetPackage, intent, 3930 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, null, 3931 null, null, options, ignoreTargetSecurity, userId, null, null); 3932 return ret; 3933 } catch (SecurityException e) { 3934 // XXX need to figure out how to propagate to original app. 3935 // A SecurityException here is generally actually a fault of the original 3936 // calling activity (such as a fairly granting permissions), so propagate it 3937 // back to them. 3938 /* 3939 StringBuilder msg = new StringBuilder(); 3940 msg.append("While launching"); 3941 msg.append(intent.toString()); 3942 msg.append(": "); 3943 msg.append(e.getMessage()); 3944 */ 3945 throw e; 3946 } 3947 } 3948 3949 @Override startActivityAndWait(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId)3950 public final WaitResult startActivityAndWait(IApplicationThread caller, String callingPackage, 3951 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3952 int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) { 3953 enforceNotIsolatedCaller("startActivityAndWait"); 3954 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3955 false, ALLOW_FULL_ONLY, "startActivityAndWait", null); 3956 WaitResult res = new WaitResult(); 3957 // TODO: Switch to user app stacks here. 3958 mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, 3959 null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, res, null, 3960 options, false, userId, null, null); 3961 return res; 3962 } 3963 3964 @Override startActivityWithConfig(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, Configuration config, Bundle options, int userId)3965 public final int startActivityWithConfig(IApplicationThread caller, String callingPackage, 3966 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, 3967 int startFlags, Configuration config, Bundle options, int userId) { 3968 enforceNotIsolatedCaller("startActivityWithConfig"); 3969 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 3970 false, ALLOW_FULL_ONLY, "startActivityWithConfig", null); 3971 // TODO: Switch to user app stacks here. 3972 int ret = mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, 3973 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 3974 null, null, config, options, false, userId, null, null); 3975 return ret; 3976 } 3977 3978 @Override startActivityIntentSender(IApplicationThread caller, IntentSender intent, Intent fillInIntent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle options)3979 public int startActivityIntentSender(IApplicationThread caller, IntentSender intent, 3980 Intent fillInIntent, String resolvedType, IBinder resultTo, String resultWho, 3981 int requestCode, int flagsMask, int flagsValues, Bundle options) 3982 throws TransactionTooLargeException { 3983 enforceNotIsolatedCaller("startActivityIntentSender"); 3984 // Refuse possible leaked file descriptors 3985 if (fillInIntent != null && fillInIntent.hasFileDescriptors()) { 3986 throw new IllegalArgumentException("File descriptors passed in Intent"); 3987 } 3988 3989 IIntentSender sender = intent.getTarget(); 3990 if (!(sender instanceof PendingIntentRecord)) { 3991 throw new IllegalArgumentException("Bad PendingIntent object"); 3992 } 3993 3994 PendingIntentRecord pir = (PendingIntentRecord)sender; 3995 3996 synchronized (this) { 3997 // If this is coming from the currently resumed activity, it is 3998 // effectively saying that app switches are allowed at this point. 3999 final ActivityStack stack = getFocusedStack(); 4000 if (stack.mResumedActivity != null && 4001 stack.mResumedActivity.info.applicationInfo.uid == Binder.getCallingUid()) { 4002 mAppSwitchesAllowedTime = 0; 4003 } 4004 } 4005 int ret = pir.sendInner(0, fillInIntent, resolvedType, null, null, 4006 resultTo, resultWho, requestCode, flagsMask, flagsValues, options, null); 4007 return ret; 4008 } 4009 4010 @Override startVoiceActivity(String callingPackage, int callingPid, int callingUid, Intent intent, String resolvedType, IVoiceInteractionSession session, IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId)4011 public int startVoiceActivity(String callingPackage, int callingPid, int callingUid, 4012 Intent intent, String resolvedType, IVoiceInteractionSession session, 4013 IVoiceInteractor interactor, int startFlags, ProfilerInfo profilerInfo, 4014 Bundle options, int userId) { 4015 if (checkCallingPermission(Manifest.permission.BIND_VOICE_INTERACTION) 4016 != PackageManager.PERMISSION_GRANTED) { 4017 String msg = "Permission Denial: startVoiceActivity() from pid=" 4018 + Binder.getCallingPid() 4019 + ", uid=" + Binder.getCallingUid() 4020 + " requires " + android.Manifest.permission.BIND_VOICE_INTERACTION; 4021 Slog.w(TAG, msg); 4022 throw new SecurityException(msg); 4023 } 4024 if (session == null || interactor == null) { 4025 throw new NullPointerException("null session or interactor"); 4026 } 4027 userId = handleIncomingUser(callingPid, callingUid, userId, 4028 false, ALLOW_FULL_ONLY, "startVoiceActivity", null); 4029 // TODO: Switch to user app stacks here. 4030 return mStackSupervisor.startActivityMayWait(null, callingUid, callingPackage, intent, 4031 resolvedType, session, interactor, null, null, 0, startFlags, profilerInfo, null, 4032 null, options, false, userId, null, null); 4033 } 4034 4035 @Override setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake)4036 public void setVoiceKeepAwake(IVoiceInteractionSession session, boolean keepAwake) { 4037 synchronized (this) { 4038 if (mRunningVoice != null && mRunningVoice.asBinder() == session.asBinder()) { 4039 if (keepAwake) { 4040 mVoiceWakeLock.acquire(); 4041 } else { 4042 mVoiceWakeLock.release(); 4043 } 4044 } 4045 } 4046 } 4047 4048 @Override startNextMatchingActivity(IBinder callingActivity, Intent intent, Bundle options)4049 public boolean startNextMatchingActivity(IBinder callingActivity, 4050 Intent intent, Bundle options) { 4051 // Refuse possible leaked file descriptors 4052 if (intent != null && intent.hasFileDescriptors() == true) { 4053 throw new IllegalArgumentException("File descriptors passed in Intent"); 4054 } 4055 4056 synchronized (this) { 4057 final ActivityRecord r = ActivityRecord.isInStackLocked(callingActivity); 4058 if (r == null) { 4059 ActivityOptions.abort(options); 4060 return false; 4061 } 4062 if (r.app == null || r.app.thread == null) { 4063 // The caller is not running... d'oh! 4064 ActivityOptions.abort(options); 4065 return false; 4066 } 4067 intent = new Intent(intent); 4068 // The caller is not allowed to change the data. 4069 intent.setDataAndType(r.intent.getData(), r.intent.getType()); 4070 // And we are resetting to find the next component... 4071 intent.setComponent(null); 4072 4073 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4074 4075 ActivityInfo aInfo = null; 4076 try { 4077 List<ResolveInfo> resolves = 4078 AppGlobals.getPackageManager().queryIntentActivities( 4079 intent, r.resolvedType, 4080 PackageManager.MATCH_DEFAULT_ONLY | STOCK_PM_FLAGS, 4081 UserHandle.getCallingUserId()); 4082 4083 // Look for the original activity in the list... 4084 final int N = resolves != null ? resolves.size() : 0; 4085 for (int i=0; i<N; i++) { 4086 ResolveInfo rInfo = resolves.get(i); 4087 if (rInfo.activityInfo.packageName.equals(r.packageName) 4088 && rInfo.activityInfo.name.equals(r.info.name)) { 4089 // We found the current one... the next matching is 4090 // after it. 4091 i++; 4092 if (i<N) { 4093 aInfo = resolves.get(i).activityInfo; 4094 } 4095 if (debug) { 4096 Slog.v(TAG, "Next matching activity: found current " + r.packageName 4097 + "/" + r.info.name); 4098 Slog.v(TAG, "Next matching activity: next is " + aInfo.packageName 4099 + "/" + aInfo.name); 4100 } 4101 break; 4102 } 4103 } 4104 } catch (RemoteException e) { 4105 } 4106 4107 if (aInfo == null) { 4108 // Nobody who is next! 4109 ActivityOptions.abort(options); 4110 if (debug) Slog.d(TAG, "Next matching activity: nothing found"); 4111 return false; 4112 } 4113 4114 intent.setComponent(new ComponentName( 4115 aInfo.applicationInfo.packageName, aInfo.name)); 4116 intent.setFlags(intent.getFlags()&~( 4117 Intent.FLAG_ACTIVITY_FORWARD_RESULT| 4118 Intent.FLAG_ACTIVITY_CLEAR_TOP| 4119 Intent.FLAG_ACTIVITY_MULTIPLE_TASK| 4120 Intent.FLAG_ACTIVITY_NEW_TASK)); 4121 4122 // Okay now we need to start the new activity, replacing the 4123 // currently running activity. This is a little tricky because 4124 // we want to start the new one as if the current one is finished, 4125 // but not finish the current one first so that there is no flicker. 4126 // And thus... 4127 final boolean wasFinishing = r.finishing; 4128 r.finishing = true; 4129 4130 // Propagate reply information over to the new activity. 4131 final ActivityRecord resultTo = r.resultTo; 4132 final String resultWho = r.resultWho; 4133 final int requestCode = r.requestCode; 4134 r.resultTo = null; 4135 if (resultTo != null) { 4136 resultTo.removeResultsLocked(r, resultWho, requestCode); 4137 } 4138 4139 final long origId = Binder.clearCallingIdentity(); 4140 int res = mStackSupervisor.startActivityLocked(r.app.thread, intent, 4141 r.resolvedType, aInfo, null, null, resultTo != null ? resultTo.appToken : null, 4142 resultWho, requestCode, -1, r.launchedFromUid, r.launchedFromPackage, 4143 -1, r.launchedFromUid, 0, options, false, false, null, null, null); 4144 Binder.restoreCallingIdentity(origId); 4145 4146 r.finishing = wasFinishing; 4147 if (res != ActivityManager.START_SUCCESS) { 4148 return false; 4149 } 4150 return true; 4151 } 4152 } 4153 4154 @Override startActivityFromRecents(int taskId, Bundle options)4155 public final int startActivityFromRecents(int taskId, Bundle options) { 4156 if (checkCallingPermission(START_TASKS_FROM_RECENTS) != PackageManager.PERMISSION_GRANTED) { 4157 String msg = "Permission Denial: startActivityFromRecents called without " + 4158 START_TASKS_FROM_RECENTS; 4159 Slog.w(TAG, msg); 4160 throw new SecurityException(msg); 4161 } 4162 return startActivityFromRecentsInner(taskId, options); 4163 } 4164 startActivityFromRecentsInner(int taskId, Bundle options)4165 final int startActivityFromRecentsInner(int taskId, Bundle options) { 4166 final TaskRecord task; 4167 final int callingUid; 4168 final String callingPackage; 4169 final Intent intent; 4170 final int userId; 4171 synchronized (this) { 4172 task = mStackSupervisor.anyTaskForIdLocked(taskId); 4173 if (task == null) { 4174 throw new IllegalArgumentException("Task " + taskId + " not found."); 4175 } 4176 if (task.getRootActivity() != null) { 4177 moveTaskToFrontLocked(task.taskId, 0, null); 4178 return ActivityManager.START_TASK_TO_FRONT; 4179 } 4180 callingUid = task.mCallingUid; 4181 callingPackage = task.mCallingPackage; 4182 intent = task.intent; 4183 intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY); 4184 userId = task.userId; 4185 } 4186 return startActivityInPackage(callingUid, callingPackage, intent, null, null, null, 0, 0, 4187 options, userId, null, task); 4188 } 4189 startActivityInPackage(int uid, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, Bundle options, int userId, IActivityContainer container, TaskRecord inTask)4190 final int startActivityInPackage(int uid, String callingPackage, 4191 Intent intent, String resolvedType, IBinder resultTo, 4192 String resultWho, int requestCode, int startFlags, Bundle options, int userId, 4193 IActivityContainer container, TaskRecord inTask) { 4194 4195 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 4196 false, ALLOW_FULL_ONLY, "startActivityInPackage", null); 4197 4198 // TODO: Switch to user app stacks here. 4199 int ret = mStackSupervisor.startActivityMayWait(null, uid, callingPackage, intent, 4200 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, 4201 null, null, null, options, false, userId, container, inTask); 4202 return ret; 4203 } 4204 4205 @Override startActivities(IApplicationThread caller, String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options, int userId)4206 public final int startActivities(IApplicationThread caller, String callingPackage, 4207 Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options, 4208 int userId) { 4209 enforceNotIsolatedCaller("startActivities"); 4210 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 4211 false, ALLOW_FULL_ONLY, "startActivity", null); 4212 // TODO: Switch to user app stacks here. 4213 int ret = mStackSupervisor.startActivities(caller, -1, callingPackage, intents, 4214 resolvedTypes, resultTo, options, userId); 4215 return ret; 4216 } 4217 startActivitiesInPackage(int uid, String callingPackage, Intent[] intents, String[] resolvedTypes, IBinder resultTo, Bundle options, int userId)4218 final int startActivitiesInPackage(int uid, String callingPackage, 4219 Intent[] intents, String[] resolvedTypes, IBinder resultTo, 4220 Bundle options, int userId) { 4221 4222 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 4223 false, ALLOW_FULL_ONLY, "startActivityInPackage", null); 4224 // TODO: Switch to user app stacks here. 4225 int ret = mStackSupervisor.startActivities(null, uid, callingPackage, intents, resolvedTypes, 4226 resultTo, options, userId); 4227 return ret; 4228 } 4229 4230 @Override reportActivityFullyDrawn(IBinder token)4231 public void reportActivityFullyDrawn(IBinder token) { 4232 synchronized (this) { 4233 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4234 if (r == null) { 4235 return; 4236 } 4237 r.reportFullyDrawnLocked(); 4238 } 4239 } 4240 4241 @Override setRequestedOrientation(IBinder token, int requestedOrientation)4242 public void setRequestedOrientation(IBinder token, int requestedOrientation) { 4243 synchronized (this) { 4244 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4245 if (r == null) { 4246 return; 4247 } 4248 if (r.task != null && r.task.mResizeable) { 4249 // Fixed screen orientation isn't supported with resizeable activities. 4250 return; 4251 } 4252 final long origId = Binder.clearCallingIdentity(); 4253 mWindowManager.setAppOrientation(r.appToken, requestedOrientation); 4254 Configuration config = mWindowManager.updateOrientationFromAppTokens( 4255 mConfiguration, r.mayFreezeScreenLocked(r.app) ? r.appToken : null); 4256 if (config != null) { 4257 r.frozenBeforeDestroy = true; 4258 if (!updateConfigurationLocked(config, r, false, false)) { 4259 mStackSupervisor.resumeTopActivitiesLocked(); 4260 } 4261 } 4262 Binder.restoreCallingIdentity(origId); 4263 } 4264 } 4265 4266 @Override getRequestedOrientation(IBinder token)4267 public int getRequestedOrientation(IBinder token) { 4268 synchronized (this) { 4269 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4270 if (r == null) { 4271 return ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED; 4272 } 4273 return mWindowManager.getAppOrientation(r.appToken); 4274 } 4275 } 4276 4277 /** 4278 * This is the internal entry point for handling Activity.finish(). 4279 * 4280 * @param token The Binder token referencing the Activity we want to finish. 4281 * @param resultCode Result code, if any, from this Activity. 4282 * @param resultData Result data (Intent), if any, from this Activity. 4283 * @param finishTask Whether to finish the task associated with this Activity. Only applies to 4284 * the root Activity in the task. 4285 * 4286 * @return Returns true if the activity successfully finished, or false if it is still running. 4287 */ 4288 @Override finishActivity(IBinder token, int resultCode, Intent resultData, boolean finishTask)4289 public final boolean finishActivity(IBinder token, int resultCode, Intent resultData, 4290 boolean finishTask) { 4291 // Refuse possible leaked file descriptors 4292 if (resultData != null && resultData.hasFileDescriptors() == true) { 4293 throw new IllegalArgumentException("File descriptors passed in Intent"); 4294 } 4295 4296 synchronized(this) { 4297 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4298 if (r == null) { 4299 return true; 4300 } 4301 // Keep track of the root activity of the task before we finish it 4302 TaskRecord tr = r.task; 4303 ActivityRecord rootR = tr.getRootActivity(); 4304 if (rootR == null) { 4305 Slog.w(TAG, "Finishing task with all activities already finished"); 4306 } 4307 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps can 4308 // finish. 4309 if (tr.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV && rootR == r && 4310 mStackSupervisor.isLastLockedTask(tr)) { 4311 Slog.i(TAG, "Not finishing task in lock task mode"); 4312 mStackSupervisor.showLockTaskToast(); 4313 return false; 4314 } 4315 if (mController != null) { 4316 // Find the first activity that is not finishing. 4317 ActivityRecord next = r.task.stack.topRunningActivityLocked(token, 0); 4318 if (next != null) { 4319 // ask watcher if this is allowed 4320 boolean resumeOK = true; 4321 try { 4322 resumeOK = mController.activityResuming(next.packageName); 4323 } catch (RemoteException e) { 4324 mController = null; 4325 Watchdog.getInstance().setActivityController(null); 4326 } 4327 4328 if (!resumeOK) { 4329 Slog.i(TAG, "Not finishing activity because controller resumed"); 4330 return false; 4331 } 4332 } 4333 } 4334 final long origId = Binder.clearCallingIdentity(); 4335 try { 4336 boolean res; 4337 if (finishTask && r == rootR) { 4338 // If requested, remove the task that is associated to this activity only if it 4339 // was the root activity in the task. The result code and data is ignored 4340 // because we don't support returning them across task boundaries. 4341 res = removeTaskByIdLocked(tr.taskId, false); 4342 if (!res) { 4343 Slog.i(TAG, "Removing task failed to finish activity"); 4344 } 4345 } else { 4346 res = tr.stack.requestFinishActivityLocked(token, resultCode, 4347 resultData, "app-request", true); 4348 if (!res) { 4349 Slog.i(TAG, "Failed to finish by app-request"); 4350 } 4351 } 4352 return res; 4353 } finally { 4354 Binder.restoreCallingIdentity(origId); 4355 } 4356 } 4357 } 4358 4359 @Override finishHeavyWeightApp()4360 public final void finishHeavyWeightApp() { 4361 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4362 != PackageManager.PERMISSION_GRANTED) { 4363 String msg = "Permission Denial: finishHeavyWeightApp() from pid=" 4364 + Binder.getCallingPid() 4365 + ", uid=" + Binder.getCallingUid() 4366 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 4367 Slog.w(TAG, msg); 4368 throw new SecurityException(msg); 4369 } 4370 4371 synchronized(this) { 4372 if (mHeavyWeightProcess == null) { 4373 return; 4374 } 4375 4376 ArrayList<ActivityRecord> activities = new ArrayList<>(mHeavyWeightProcess.activities); 4377 for (int i = 0; i < activities.size(); i++) { 4378 ActivityRecord r = activities.get(i); 4379 if (!r.finishing && r.isInStackLocked()) { 4380 r.task.stack.finishActivityLocked(r, Activity.RESULT_CANCELED, 4381 null, "finish-heavy", true); 4382 } 4383 } 4384 4385 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 4386 mHeavyWeightProcess.userId, 0)); 4387 mHeavyWeightProcess = null; 4388 } 4389 } 4390 4391 @Override crashApplication(int uid, int initialPid, String packageName, String message)4392 public void crashApplication(int uid, int initialPid, String packageName, 4393 String message) { 4394 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 4395 != PackageManager.PERMISSION_GRANTED) { 4396 String msg = "Permission Denial: crashApplication() from pid=" 4397 + Binder.getCallingPid() 4398 + ", uid=" + Binder.getCallingUid() 4399 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 4400 Slog.w(TAG, msg); 4401 throw new SecurityException(msg); 4402 } 4403 4404 synchronized(this) { 4405 ProcessRecord proc = null; 4406 4407 // Figure out which process to kill. We don't trust that initialPid 4408 // still has any relation to current pids, so must scan through the 4409 // list. 4410 synchronized (mPidsSelfLocked) { 4411 for (int i=0; i<mPidsSelfLocked.size(); i++) { 4412 ProcessRecord p = mPidsSelfLocked.valueAt(i); 4413 if (p.uid != uid) { 4414 continue; 4415 } 4416 if (p.pid == initialPid) { 4417 proc = p; 4418 break; 4419 } 4420 if (p.pkgList.containsKey(packageName)) { 4421 proc = p; 4422 } 4423 } 4424 } 4425 4426 if (proc == null) { 4427 Slog.w(TAG, "crashApplication: nothing for uid=" + uid 4428 + " initialPid=" + initialPid 4429 + " packageName=" + packageName); 4430 return; 4431 } 4432 4433 if (proc.thread != null) { 4434 if (proc.pid == Process.myPid()) { 4435 Log.w(TAG, "crashApplication: trying to crash self!"); 4436 return; 4437 } 4438 long ident = Binder.clearCallingIdentity(); 4439 try { 4440 proc.thread.scheduleCrash(message); 4441 } catch (RemoteException e) { 4442 } 4443 Binder.restoreCallingIdentity(ident); 4444 } 4445 } 4446 } 4447 4448 @Override finishSubActivity(IBinder token, String resultWho, int requestCode)4449 public final void finishSubActivity(IBinder token, String resultWho, 4450 int requestCode) { 4451 synchronized(this) { 4452 final long origId = Binder.clearCallingIdentity(); 4453 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4454 if (r != null) { 4455 r.task.stack.finishSubActivityLocked(r, resultWho, requestCode); 4456 } 4457 Binder.restoreCallingIdentity(origId); 4458 } 4459 } 4460 4461 @Override finishActivityAffinity(IBinder token)4462 public boolean finishActivityAffinity(IBinder token) { 4463 synchronized(this) { 4464 final long origId = Binder.clearCallingIdentity(); 4465 try { 4466 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4467 if (r == null) { 4468 return false; 4469 } 4470 4471 // Do not allow task to finish if last task in lockTask mode. Launchable priv-apps 4472 // can finish. 4473 final TaskRecord task = r.task; 4474 if (task.mLockTaskAuth != LOCK_TASK_AUTH_LAUNCHABLE_PRIV && 4475 mStackSupervisor.isLastLockedTask(task) && task.getRootActivity() == r) { 4476 mStackSupervisor.showLockTaskToast(); 4477 return false; 4478 } 4479 return task.stack.finishActivityAffinityLocked(r); 4480 } finally { 4481 Binder.restoreCallingIdentity(origId); 4482 } 4483 } 4484 } 4485 4486 @Override finishVoiceTask(IVoiceInteractionSession session)4487 public void finishVoiceTask(IVoiceInteractionSession session) { 4488 synchronized(this) { 4489 final long origId = Binder.clearCallingIdentity(); 4490 try { 4491 mStackSupervisor.finishVoiceTask(session); 4492 } finally { 4493 Binder.restoreCallingIdentity(origId); 4494 } 4495 } 4496 4497 } 4498 4499 @Override releaseActivityInstance(IBinder token)4500 public boolean releaseActivityInstance(IBinder token) { 4501 synchronized(this) { 4502 final long origId = Binder.clearCallingIdentity(); 4503 try { 4504 ActivityRecord r = ActivityRecord.isInStackLocked(token); 4505 if (r == null) { 4506 return false; 4507 } 4508 return r.task.stack.safelyDestroyActivityLocked(r, "app-req"); 4509 } finally { 4510 Binder.restoreCallingIdentity(origId); 4511 } 4512 } 4513 } 4514 4515 @Override releaseSomeActivities(IApplicationThread appInt)4516 public void releaseSomeActivities(IApplicationThread appInt) { 4517 synchronized(this) { 4518 final long origId = Binder.clearCallingIdentity(); 4519 try { 4520 ProcessRecord app = getRecordForAppLocked(appInt); 4521 mStackSupervisor.releaseSomeActivitiesLocked(app, "low-mem"); 4522 } finally { 4523 Binder.restoreCallingIdentity(origId); 4524 } 4525 } 4526 } 4527 4528 @Override willActivityBeVisible(IBinder token)4529 public boolean willActivityBeVisible(IBinder token) { 4530 synchronized(this) { 4531 ActivityStack stack = ActivityRecord.getStackLocked(token); 4532 if (stack != null) { 4533 return stack.willActivityBeVisibleLocked(token); 4534 } 4535 return false; 4536 } 4537 } 4538 4539 @Override overridePendingTransition(IBinder token, String packageName, int enterAnim, int exitAnim)4540 public void overridePendingTransition(IBinder token, String packageName, 4541 int enterAnim, int exitAnim) { 4542 synchronized(this) { 4543 ActivityRecord self = ActivityRecord.isInStackLocked(token); 4544 if (self == null) { 4545 return; 4546 } 4547 4548 final long origId = Binder.clearCallingIdentity(); 4549 4550 if (self.state == ActivityState.RESUMED 4551 || self.state == ActivityState.PAUSING) { 4552 mWindowManager.overridePendingAppTransition(packageName, 4553 enterAnim, exitAnim, null); 4554 } 4555 4556 Binder.restoreCallingIdentity(origId); 4557 } 4558 } 4559 4560 /** 4561 * Main function for removing an existing process from the activity manager 4562 * as a result of that process going away. Clears out all connections 4563 * to the process. 4564 */ handleAppDiedLocked(ProcessRecord app, boolean restarting, boolean allowRestart)4565 private final void handleAppDiedLocked(ProcessRecord app, 4566 boolean restarting, boolean allowRestart) { 4567 int pid = app.pid; 4568 boolean kept = cleanUpApplicationRecordLocked(app, restarting, allowRestart, -1); 4569 if (!kept && !restarting) { 4570 removeLruProcessLocked(app); 4571 if (pid > 0) { 4572 ProcessList.remove(pid); 4573 } 4574 } 4575 4576 if (mProfileProc == app) { 4577 clearProfilerLocked(); 4578 } 4579 4580 // Remove this application's activities from active lists. 4581 boolean hasVisibleActivities = mStackSupervisor.handleAppDiedLocked(app); 4582 4583 app.activities.clear(); 4584 4585 if (app.instrumentationClass != null) { 4586 Slog.w(TAG, "Crash of app " + app.processName 4587 + " running instrumentation " + app.instrumentationClass); 4588 Bundle info = new Bundle(); 4589 info.putString("shortMsg", "Process crashed."); 4590 finishInstrumentationLocked(app, Activity.RESULT_CANCELED, info); 4591 } 4592 4593 if (!restarting && hasVisibleActivities && !mStackSupervisor.resumeTopActivitiesLocked()) { 4594 // If there was nothing to resume, and we are not already 4595 // restarting this process, but there is a visible activity that 4596 // is hosted by the process... then make sure all visible 4597 // activities are running, taking care of restarting this 4598 // process. 4599 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 4600 } 4601 } 4602 getLRURecordIndexForAppLocked(IApplicationThread thread)4603 private final int getLRURecordIndexForAppLocked(IApplicationThread thread) { 4604 IBinder threadBinder = thread.asBinder(); 4605 // Find the application record. 4606 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4607 ProcessRecord rec = mLruProcesses.get(i); 4608 if (rec.thread != null && rec.thread.asBinder() == threadBinder) { 4609 return i; 4610 } 4611 } 4612 return -1; 4613 } 4614 getRecordForAppLocked( IApplicationThread thread)4615 final ProcessRecord getRecordForAppLocked( 4616 IApplicationThread thread) { 4617 if (thread == null) { 4618 return null; 4619 } 4620 4621 int appIndex = getLRURecordIndexForAppLocked(thread); 4622 return appIndex >= 0 ? mLruProcesses.get(appIndex) : null; 4623 } 4624 doLowMemReportIfNeededLocked(ProcessRecord dyingProc)4625 final void doLowMemReportIfNeededLocked(ProcessRecord dyingProc) { 4626 // If there are no longer any background processes running, 4627 // and the app that died was not running instrumentation, 4628 // then tell everyone we are now low on memory. 4629 boolean haveBg = false; 4630 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4631 ProcessRecord rec = mLruProcesses.get(i); 4632 if (rec.thread != null 4633 && rec.setProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 4634 haveBg = true; 4635 break; 4636 } 4637 } 4638 4639 if (!haveBg) { 4640 boolean doReport = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 4641 if (doReport) { 4642 long now = SystemClock.uptimeMillis(); 4643 if (now < (mLastMemUsageReportTime+5*60*1000)) { 4644 doReport = false; 4645 } else { 4646 mLastMemUsageReportTime = now; 4647 } 4648 } 4649 final ArrayList<ProcessMemInfo> memInfos 4650 = doReport ? new ArrayList<ProcessMemInfo>(mLruProcesses.size()) : null; 4651 EventLog.writeEvent(EventLogTags.AM_LOW_MEMORY, mLruProcesses.size()); 4652 long now = SystemClock.uptimeMillis(); 4653 for (int i=mLruProcesses.size()-1; i>=0; i--) { 4654 ProcessRecord rec = mLruProcesses.get(i); 4655 if (rec == dyingProc || rec.thread == null) { 4656 continue; 4657 } 4658 if (doReport) { 4659 memInfos.add(new ProcessMemInfo(rec.processName, rec.pid, rec.setAdj, 4660 rec.setProcState, rec.adjType, rec.makeAdjReason())); 4661 } 4662 if ((rec.lastLowMemory+GC_MIN_INTERVAL) <= now) { 4663 // The low memory report is overriding any current 4664 // state for a GC request. Make sure to do 4665 // heavy/important/visible/foreground processes first. 4666 if (rec.setAdj <= ProcessList.HEAVY_WEIGHT_APP_ADJ) { 4667 rec.lastRequestedGc = 0; 4668 } else { 4669 rec.lastRequestedGc = rec.lastLowMemory; 4670 } 4671 rec.reportLowMemory = true; 4672 rec.lastLowMemory = now; 4673 mProcessesToGc.remove(rec); 4674 addProcessToGcListLocked(rec); 4675 } 4676 } 4677 if (doReport) { 4678 Message msg = mHandler.obtainMessage(REPORT_MEM_USAGE_MSG, memInfos); 4679 mHandler.sendMessage(msg); 4680 } 4681 scheduleAppGcsLocked(); 4682 } 4683 } 4684 appDiedLocked(ProcessRecord app)4685 final void appDiedLocked(ProcessRecord app) { 4686 appDiedLocked(app, app.pid, app.thread, false); 4687 } 4688 appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, boolean fromBinderDied)4689 final void appDiedLocked(ProcessRecord app, int pid, IApplicationThread thread, 4690 boolean fromBinderDied) { 4691 // First check if this ProcessRecord is actually active for the pid. 4692 synchronized (mPidsSelfLocked) { 4693 ProcessRecord curProc = mPidsSelfLocked.get(pid); 4694 if (curProc != app) { 4695 Slog.w(TAG, "Spurious death for " + app + ", curProc for " + pid + ": " + curProc); 4696 return; 4697 } 4698 } 4699 4700 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 4701 synchronized (stats) { 4702 stats.noteProcessDiedLocked(app.info.uid, pid); 4703 } 4704 4705 if (!app.killed) { 4706 if (!fromBinderDied) { 4707 Process.killProcessQuiet(pid); 4708 } 4709 killProcessGroup(app.uid, pid); 4710 app.killed = true; 4711 } 4712 4713 // Clean up already done if the process has been re-started. 4714 if (app.pid == pid && app.thread != null && 4715 app.thread.asBinder() == thread.asBinder()) { 4716 boolean doLowMem = app.instrumentationClass == null; 4717 boolean doOomAdj = doLowMem; 4718 if (!app.killedByAm) { 4719 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 4720 + ") has died"); 4721 mAllowLowerMemLevel = true; 4722 } else { 4723 // Note that we always want to do oom adj to update our state with the 4724 // new number of procs. 4725 mAllowLowerMemLevel = false; 4726 doLowMem = false; 4727 } 4728 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 4729 if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 4730 "Dying app: " + app + ", pid: " + pid + ", thread: " + thread.asBinder()); 4731 handleAppDiedLocked(app, false, true); 4732 4733 if (doOomAdj) { 4734 updateOomAdjLocked(); 4735 } 4736 if (doLowMem) { 4737 doLowMemReportIfNeededLocked(app); 4738 } 4739 } else if (app.pid != pid) { 4740 // A new process has already been started. 4741 Slog.i(TAG, "Process " + app.processName + " (pid " + pid 4742 + ") has died and restarted (pid " + app.pid + ")."); 4743 EventLog.writeEvent(EventLogTags.AM_PROC_DIED, app.userId, app.pid, app.processName); 4744 } else if (DEBUG_PROCESSES) { 4745 Slog.d(TAG_PROCESSES, "Received spurious death notification for thread " 4746 + thread.asBinder()); 4747 } 4748 } 4749 4750 /** 4751 * If a stack trace dump file is configured, dump process stack traces. 4752 * @param clearTraces causes the dump file to be erased prior to the new 4753 * traces being written, if true; when false, the new traces will be 4754 * appended to any existing file content. 4755 * @param firstPids of dalvik VM processes to dump stack traces for first 4756 * @param lastPids of dalvik VM processes to dump stack traces for last 4757 * @param nativeProcs optional list of native process names to dump stack crawls 4758 * @return file containing stack traces, or null if no dump file is configured 4759 */ dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs)4760 public static File dumpStackTraces(boolean clearTraces, ArrayList<Integer> firstPids, 4761 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) { 4762 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 4763 if (tracesPath == null || tracesPath.length() == 0) { 4764 return null; 4765 } 4766 4767 File tracesFile = new File(tracesPath); 4768 try { 4769 File tracesDir = tracesFile.getParentFile(); 4770 if (!tracesDir.exists()) { 4771 tracesDir.mkdirs(); 4772 if (!SELinux.restorecon(tracesDir)) { 4773 return null; 4774 } 4775 } 4776 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 4777 4778 if (clearTraces && tracesFile.exists()) tracesFile.delete(); 4779 tracesFile.createNewFile(); 4780 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 4781 } catch (IOException e) { 4782 Slog.w(TAG, "Unable to prepare ANR traces file: " + tracesPath, e); 4783 return null; 4784 } 4785 4786 dumpStackTraces(tracesPath, firstPids, processCpuTracker, lastPids, nativeProcs); 4787 return tracesFile; 4788 } 4789 dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids, ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs)4790 private static void dumpStackTraces(String tracesPath, ArrayList<Integer> firstPids, 4791 ProcessCpuTracker processCpuTracker, SparseArray<Boolean> lastPids, String[] nativeProcs) { 4792 // Use a FileObserver to detect when traces finish writing. 4793 // The order of traces is considered important to maintain for legibility. 4794 FileObserver observer = new FileObserver(tracesPath, FileObserver.CLOSE_WRITE) { 4795 @Override 4796 public synchronized void onEvent(int event, String path) { notify(); } 4797 }; 4798 4799 try { 4800 observer.startWatching(); 4801 4802 // First collect all of the stacks of the most important pids. 4803 if (firstPids != null) { 4804 try { 4805 int num = firstPids.size(); 4806 for (int i = 0; i < num; i++) { 4807 synchronized (observer) { 4808 Process.sendSignal(firstPids.get(i), Process.SIGNAL_QUIT); 4809 observer.wait(200); // Wait for write-close, give up after 200msec 4810 } 4811 } 4812 } catch (InterruptedException e) { 4813 Slog.wtf(TAG, e); 4814 } 4815 } 4816 4817 // Next collect the stacks of the native pids 4818 if (nativeProcs != null) { 4819 int[] pids = Process.getPidsForCommands(nativeProcs); 4820 if (pids != null) { 4821 for (int pid : pids) { 4822 Debug.dumpNativeBacktraceToFile(pid, tracesPath); 4823 } 4824 } 4825 } 4826 4827 // Lastly, measure CPU usage. 4828 if (processCpuTracker != null) { 4829 processCpuTracker.init(); 4830 System.gc(); 4831 processCpuTracker.update(); 4832 try { 4833 synchronized (processCpuTracker) { 4834 processCpuTracker.wait(500); // measure over 1/2 second. 4835 } 4836 } catch (InterruptedException e) { 4837 } 4838 processCpuTracker.update(); 4839 4840 // We'll take the stack crawls of just the top apps using CPU. 4841 final int N = processCpuTracker.countWorkingStats(); 4842 int numProcs = 0; 4843 for (int i=0; i<N && numProcs<5; i++) { 4844 ProcessCpuTracker.Stats stats = processCpuTracker.getWorkingStats(i); 4845 if (lastPids.indexOfKey(stats.pid) >= 0) { 4846 numProcs++; 4847 try { 4848 synchronized (observer) { 4849 Process.sendSignal(stats.pid, Process.SIGNAL_QUIT); 4850 observer.wait(200); // Wait for write-close, give up after 200msec 4851 } 4852 } catch (InterruptedException e) { 4853 Slog.wtf(TAG, e); 4854 } 4855 4856 } 4857 } 4858 } 4859 } finally { 4860 observer.stopWatching(); 4861 } 4862 } 4863 logAppTooSlow(ProcessRecord app, long startTime, String msg)4864 final void logAppTooSlow(ProcessRecord app, long startTime, String msg) { 4865 if (true || IS_USER_BUILD) { 4866 return; 4867 } 4868 String tracesPath = SystemProperties.get("dalvik.vm.stack-trace-file", null); 4869 if (tracesPath == null || tracesPath.length() == 0) { 4870 return; 4871 } 4872 4873 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 4874 StrictMode.allowThreadDiskWrites(); 4875 try { 4876 final File tracesFile = new File(tracesPath); 4877 final File tracesDir = tracesFile.getParentFile(); 4878 final File tracesTmp = new File(tracesDir, "__tmp__"); 4879 try { 4880 if (!tracesDir.exists()) { 4881 tracesDir.mkdirs(); 4882 if (!SELinux.restorecon(tracesDir.getPath())) { 4883 return; 4884 } 4885 } 4886 FileUtils.setPermissions(tracesDir.getPath(), 0775, -1, -1); // drwxrwxr-x 4887 4888 if (tracesFile.exists()) { 4889 tracesTmp.delete(); 4890 tracesFile.renameTo(tracesTmp); 4891 } 4892 StringBuilder sb = new StringBuilder(); 4893 Time tobj = new Time(); 4894 tobj.set(System.currentTimeMillis()); 4895 sb.append(tobj.format("%Y-%m-%d %H:%M:%S")); 4896 sb.append(": "); 4897 TimeUtils.formatDuration(SystemClock.uptimeMillis()-startTime, sb); 4898 sb.append(" since "); 4899 sb.append(msg); 4900 FileOutputStream fos = new FileOutputStream(tracesFile); 4901 fos.write(sb.toString().getBytes()); 4902 if (app == null) { 4903 fos.write("\n*** No application process!".getBytes()); 4904 } 4905 fos.close(); 4906 FileUtils.setPermissions(tracesFile.getPath(), 0666, -1, -1); // -rw-rw-rw- 4907 } catch (IOException e) { 4908 Slog.w(TAG, "Unable to prepare slow app traces file: " + tracesPath, e); 4909 return; 4910 } 4911 4912 if (app != null) { 4913 ArrayList<Integer> firstPids = new ArrayList<Integer>(); 4914 firstPids.add(app.pid); 4915 dumpStackTraces(tracesPath, firstPids, null, null, null); 4916 } 4917 4918 File lastTracesFile = null; 4919 File curTracesFile = null; 4920 for (int i=9; i>=0; i--) { 4921 String name = String.format(Locale.US, "slow%02d.txt", i); 4922 curTracesFile = new File(tracesDir, name); 4923 if (curTracesFile.exists()) { 4924 if (lastTracesFile != null) { 4925 curTracesFile.renameTo(lastTracesFile); 4926 } else { 4927 curTracesFile.delete(); 4928 } 4929 } 4930 lastTracesFile = curTracesFile; 4931 } 4932 tracesFile.renameTo(curTracesFile); 4933 if (tracesTmp.exists()) { 4934 tracesTmp.renameTo(tracesFile); 4935 } 4936 } finally { 4937 StrictMode.setThreadPolicy(oldPolicy); 4938 } 4939 } 4940 appNotResponding(ProcessRecord app, ActivityRecord activity, ActivityRecord parent, boolean aboveSystem, final String annotation)4941 final void appNotResponding(ProcessRecord app, ActivityRecord activity, 4942 ActivityRecord parent, boolean aboveSystem, final String annotation) { 4943 ArrayList<Integer> firstPids = new ArrayList<Integer>(5); 4944 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20); 4945 4946 if (mController != null) { 4947 try { 4948 // 0 == continue, -1 = kill process immediately 4949 int res = mController.appEarlyNotResponding(app.processName, app.pid, annotation); 4950 if (res < 0 && app.pid != MY_PID) { 4951 app.kill("anr", true); 4952 } 4953 } catch (RemoteException e) { 4954 mController = null; 4955 Watchdog.getInstance().setActivityController(null); 4956 } 4957 } 4958 4959 long anrTime = SystemClock.uptimeMillis(); 4960 if (MONITOR_CPU_USAGE) { 4961 updateCpuStatsNow(); 4962 } 4963 4964 synchronized (this) { 4965 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down. 4966 if (mShuttingDown) { 4967 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation); 4968 return; 4969 } else if (app.notResponding) { 4970 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation); 4971 return; 4972 } else if (app.crashing) { 4973 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation); 4974 return; 4975 } 4976 4977 // In case we come through here for the same app before completing 4978 // this one, mark as anring now so we will bail out. 4979 app.notResponding = true; 4980 4981 // Log the ANR to the event log. 4982 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid, 4983 app.processName, app.info.flags, annotation); 4984 4985 // Dump thread traces as quickly as we can, starting with "interesting" processes. 4986 firstPids.add(app.pid); 4987 4988 int parentPid = app.pid; 4989 if (parent != null && parent.app != null && parent.app.pid > 0) parentPid = parent.app.pid; 4990 if (parentPid != app.pid) firstPids.add(parentPid); 4991 4992 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID); 4993 4994 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 4995 ProcessRecord r = mLruProcesses.get(i); 4996 if (r != null && r.thread != null) { 4997 int pid = r.pid; 4998 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) { 4999 if (r.persistent) { 5000 firstPids.add(pid); 5001 } else { 5002 lastPids.put(pid, Boolean.TRUE); 5003 } 5004 } 5005 } 5006 } 5007 } 5008 5009 // Log the ANR to the main log. 5010 StringBuilder info = new StringBuilder(); 5011 info.setLength(0); 5012 info.append("ANR in ").append(app.processName); 5013 if (activity != null && activity.shortComponentName != null) { 5014 info.append(" (").append(activity.shortComponentName).append(")"); 5015 } 5016 info.append("\n"); 5017 info.append("PID: ").append(app.pid).append("\n"); 5018 if (annotation != null) { 5019 info.append("Reason: ").append(annotation).append("\n"); 5020 } 5021 if (parent != null && parent != activity) { 5022 info.append("Parent: ").append(parent.shortComponentName).append("\n"); 5023 } 5024 5025 final ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true); 5026 5027 File tracesFile = dumpStackTraces(true, firstPids, processCpuTracker, lastPids, 5028 NATIVE_STACKS_OF_INTEREST); 5029 5030 String cpuInfo = null; 5031 if (MONITOR_CPU_USAGE) { 5032 updateCpuStatsNow(); 5033 synchronized (mProcessCpuTracker) { 5034 cpuInfo = mProcessCpuTracker.printCurrentState(anrTime); 5035 } 5036 info.append(processCpuTracker.printCurrentLoad()); 5037 info.append(cpuInfo); 5038 } 5039 5040 info.append(processCpuTracker.printCurrentState(anrTime)); 5041 5042 Slog.e(TAG, info.toString()); 5043 if (tracesFile == null) { 5044 // There is no trace file, so dump (only) the alleged culprit's threads to the log 5045 Process.sendSignal(app.pid, Process.SIGNAL_QUIT); 5046 } 5047 5048 addErrorToDropBox("anr", app, app.processName, activity, parent, annotation, 5049 cpuInfo, tracesFile, null); 5050 5051 if (mController != null) { 5052 try { 5053 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately 5054 int res = mController.appNotResponding(app.processName, app.pid, info.toString()); 5055 if (res != 0) { 5056 if (res < 0 && app.pid != MY_PID) { 5057 app.kill("anr", true); 5058 } else { 5059 synchronized (this) { 5060 mServices.scheduleServiceTimeoutLocked(app); 5061 } 5062 } 5063 return; 5064 } 5065 } catch (RemoteException e) { 5066 mController = null; 5067 Watchdog.getInstance().setActivityController(null); 5068 } 5069 } 5070 5071 // Unless configured otherwise, swallow ANRs in background processes & kill the process. 5072 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(), 5073 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0; 5074 5075 synchronized (this) { 5076 mBatteryStatsService.noteProcessAnr(app.processName, app.uid); 5077 5078 if (!showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID) { 5079 app.kill("bg anr", true); 5080 return; 5081 } 5082 5083 // Set the app's notResponding state, and look up the errorReportReceiver 5084 makeAppNotRespondingLocked(app, 5085 activity != null ? activity.shortComponentName : null, 5086 annotation != null ? "ANR " + annotation : "ANR", 5087 info.toString()); 5088 5089 // Bring up the infamous App Not Responding dialog 5090 Message msg = Message.obtain(); 5091 HashMap<String, Object> map = new HashMap<String, Object>(); 5092 msg.what = SHOW_NOT_RESPONDING_MSG; 5093 msg.obj = map; 5094 msg.arg1 = aboveSystem ? 1 : 0; 5095 map.put("app", app); 5096 if (activity != null) { 5097 map.put("activity", activity); 5098 } 5099 5100 mUiHandler.sendMessage(msg); 5101 } 5102 } 5103 showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next)5104 final void showLaunchWarningLocked(final ActivityRecord cur, final ActivityRecord next) { 5105 if (!mLaunchWarningShown) { 5106 mLaunchWarningShown = true; 5107 mUiHandler.post(new Runnable() { 5108 @Override 5109 public void run() { 5110 synchronized (ActivityManagerService.this) { 5111 final Dialog d = new LaunchWarningWindow(mContext, cur, next); 5112 d.show(); 5113 mUiHandler.postDelayed(new Runnable() { 5114 @Override 5115 public void run() { 5116 synchronized (ActivityManagerService.this) { 5117 d.dismiss(); 5118 mLaunchWarningShown = false; 5119 } 5120 } 5121 }, 4000); 5122 } 5123 } 5124 }); 5125 } 5126 } 5127 5128 @Override clearApplicationUserData(final String packageName, final IPackageDataObserver observer, int userId)5129 public boolean clearApplicationUserData(final String packageName, 5130 final IPackageDataObserver observer, int userId) { 5131 enforceNotIsolatedCaller("clearApplicationUserData"); 5132 if (packageName != null && packageName.equals(mDeviceOwnerName)) { 5133 throw new SecurityException("Clearing DeviceOwner data is forbidden."); 5134 } 5135 int uid = Binder.getCallingUid(); 5136 int pid = Binder.getCallingPid(); 5137 userId = handleIncomingUser(pid, uid, 5138 userId, false, ALLOW_FULL_ONLY, "clearApplicationUserData", null); 5139 long callingId = Binder.clearCallingIdentity(); 5140 try { 5141 IPackageManager pm = AppGlobals.getPackageManager(); 5142 int pkgUid = -1; 5143 synchronized(this) { 5144 try { 5145 pkgUid = pm.getPackageUid(packageName, userId); 5146 } catch (RemoteException e) { 5147 } 5148 if (pkgUid == -1) { 5149 Slog.w(TAG, "Invalid packageName: " + packageName); 5150 if (observer != null) { 5151 try { 5152 observer.onRemoveCompleted(packageName, false); 5153 } catch (RemoteException e) { 5154 Slog.i(TAG, "Observer no longer exists."); 5155 } 5156 } 5157 return false; 5158 } 5159 if (uid == pkgUid || checkComponentPermission( 5160 android.Manifest.permission.CLEAR_APP_USER_DATA, 5161 pid, uid, -1, true) 5162 == PackageManager.PERMISSION_GRANTED) { 5163 forceStopPackageLocked(packageName, pkgUid, "clear data"); 5164 } else { 5165 throw new SecurityException("PID " + pid + " does not have permission " 5166 + android.Manifest.permission.CLEAR_APP_USER_DATA + " to clear data" 5167 + " of package " + packageName); 5168 } 5169 5170 // Remove all tasks match the cleared application package and user 5171 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 5172 final TaskRecord tr = mRecentTasks.get(i); 5173 final String taskPackageName = 5174 tr.getBaseIntent().getComponent().getPackageName(); 5175 if (tr.userId != userId) continue; 5176 if (!taskPackageName.equals(packageName)) continue; 5177 removeTaskByIdLocked(tr.taskId, false); 5178 } 5179 } 5180 5181 try { 5182 // Clear application user data 5183 pm.clearApplicationUserData(packageName, observer, userId); 5184 5185 synchronized(this) { 5186 // Remove all permissions granted from/to this package 5187 removeUriPermissionsForPackageLocked(packageName, userId, true); 5188 } 5189 5190 Intent intent = new Intent(Intent.ACTION_PACKAGE_DATA_CLEARED, 5191 Uri.fromParts("package", packageName, null)); 5192 intent.putExtra(Intent.EXTRA_UID, pkgUid); 5193 broadcastIntentInPackage("android", Process.SYSTEM_UID, intent, 5194 null, null, 0, null, null, null, null, false, false, userId); 5195 } catch (RemoteException e) { 5196 } 5197 } finally { 5198 Binder.restoreCallingIdentity(callingId); 5199 } 5200 return true; 5201 } 5202 5203 @Override killBackgroundProcesses(final String packageName, int userId)5204 public void killBackgroundProcesses(final String packageName, int userId) { 5205 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 5206 != PackageManager.PERMISSION_GRANTED && 5207 checkCallingPermission(android.Manifest.permission.RESTART_PACKAGES) 5208 != PackageManager.PERMISSION_GRANTED) { 5209 String msg = "Permission Denial: killBackgroundProcesses() from pid=" 5210 + Binder.getCallingPid() 5211 + ", uid=" + Binder.getCallingUid() 5212 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 5213 Slog.w(TAG, msg); 5214 throw new SecurityException(msg); 5215 } 5216 5217 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 5218 userId, true, ALLOW_FULL_ONLY, "killBackgroundProcesses", null); 5219 long callingId = Binder.clearCallingIdentity(); 5220 try { 5221 IPackageManager pm = AppGlobals.getPackageManager(); 5222 synchronized(this) { 5223 int appId = -1; 5224 try { 5225 appId = UserHandle.getAppId(pm.getPackageUid(packageName, 0)); 5226 } catch (RemoteException e) { 5227 } 5228 if (appId == -1) { 5229 Slog.w(TAG, "Invalid packageName: " + packageName); 5230 return; 5231 } 5232 killPackageProcessesLocked(packageName, appId, userId, 5233 ProcessList.SERVICE_ADJ, false, true, true, false, "kill background"); 5234 } 5235 } finally { 5236 Binder.restoreCallingIdentity(callingId); 5237 } 5238 } 5239 5240 @Override killAllBackgroundProcesses()5241 public void killAllBackgroundProcesses() { 5242 if (checkCallingPermission(android.Manifest.permission.KILL_BACKGROUND_PROCESSES) 5243 != PackageManager.PERMISSION_GRANTED) { 5244 String msg = "Permission Denial: killAllBackgroundProcesses() from pid=" 5245 + Binder.getCallingPid() 5246 + ", uid=" + Binder.getCallingUid() 5247 + " requires " + android.Manifest.permission.KILL_BACKGROUND_PROCESSES; 5248 Slog.w(TAG, msg); 5249 throw new SecurityException(msg); 5250 } 5251 5252 long callingId = Binder.clearCallingIdentity(); 5253 try { 5254 synchronized(this) { 5255 ArrayList<ProcessRecord> procs = new ArrayList<ProcessRecord>(); 5256 final int NP = mProcessNames.getMap().size(); 5257 for (int ip=0; ip<NP; ip++) { 5258 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 5259 final int NA = apps.size(); 5260 for (int ia=0; ia<NA; ia++) { 5261 ProcessRecord app = apps.valueAt(ia); 5262 if (app.persistent) { 5263 // we don't kill persistent processes 5264 continue; 5265 } 5266 if (app.removed) { 5267 procs.add(app); 5268 } else if (app.setAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 5269 app.removed = true; 5270 procs.add(app); 5271 } 5272 } 5273 } 5274 5275 int N = procs.size(); 5276 for (int i=0; i<N; i++) { 5277 removeProcessLocked(procs.get(i), false, true, "kill all background"); 5278 } 5279 mAllowLowerMemLevel = true; 5280 updateOomAdjLocked(); 5281 doLowMemReportIfNeededLocked(null); 5282 } 5283 } finally { 5284 Binder.restoreCallingIdentity(callingId); 5285 } 5286 } 5287 5288 @Override forceStopPackage(final String packageName, int userId)5289 public void forceStopPackage(final String packageName, int userId) { 5290 if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES) 5291 != PackageManager.PERMISSION_GRANTED) { 5292 String msg = "Permission Denial: forceStopPackage() from pid=" 5293 + Binder.getCallingPid() 5294 + ", uid=" + Binder.getCallingUid() 5295 + " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES; 5296 Slog.w(TAG, msg); 5297 throw new SecurityException(msg); 5298 } 5299 final int callingPid = Binder.getCallingPid(); 5300 userId = handleIncomingUser(callingPid, Binder.getCallingUid(), 5301 userId, true, ALLOW_FULL_ONLY, "forceStopPackage", null); 5302 long callingId = Binder.clearCallingIdentity(); 5303 try { 5304 IPackageManager pm = AppGlobals.getPackageManager(); 5305 synchronized(this) { 5306 int[] users = userId == UserHandle.USER_ALL 5307 ? getUsersLocked() : new int[] { userId }; 5308 for (int user : users) { 5309 int pkgUid = -1; 5310 try { 5311 pkgUid = pm.getPackageUid(packageName, user); 5312 } catch (RemoteException e) { 5313 } 5314 if (pkgUid == -1) { 5315 Slog.w(TAG, "Invalid packageName: " + packageName); 5316 continue; 5317 } 5318 try { 5319 pm.setPackageStoppedState(packageName, true, user); 5320 } catch (RemoteException e) { 5321 } catch (IllegalArgumentException e) { 5322 Slog.w(TAG, "Failed trying to unstop package " 5323 + packageName + ": " + e); 5324 } 5325 if (isUserRunningLocked(user, false)) { 5326 forceStopPackageLocked(packageName, pkgUid, "from pid " + callingPid); 5327 } 5328 } 5329 } 5330 } finally { 5331 Binder.restoreCallingIdentity(callingId); 5332 } 5333 } 5334 5335 @Override addPackageDependency(String packageName)5336 public void addPackageDependency(String packageName) { 5337 synchronized (this) { 5338 int callingPid = Binder.getCallingPid(); 5339 if (callingPid == Process.myPid()) { 5340 // Yeah, um, no. 5341 return; 5342 } 5343 ProcessRecord proc; 5344 synchronized (mPidsSelfLocked) { 5345 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 5346 } 5347 if (proc != null) { 5348 if (proc.pkgDeps == null) { 5349 proc.pkgDeps = new ArraySet<String>(1); 5350 } 5351 proc.pkgDeps.add(packageName); 5352 } 5353 } 5354 } 5355 5356 /* 5357 * The pkg name and app id have to be specified. 5358 */ 5359 @Override killApplicationWithAppId(String pkg, int appid, String reason)5360 public void killApplicationWithAppId(String pkg, int appid, String reason) { 5361 if (pkg == null) { 5362 return; 5363 } 5364 // Make sure the uid is valid. 5365 if (appid < 0) { 5366 Slog.w(TAG, "Invalid appid specified for pkg : " + pkg); 5367 return; 5368 } 5369 int callerUid = Binder.getCallingUid(); 5370 // Only the system server can kill an application 5371 if (UserHandle.getAppId(callerUid) == Process.SYSTEM_UID) { 5372 // Post an aysnc message to kill the application 5373 Message msg = mHandler.obtainMessage(KILL_APPLICATION_MSG); 5374 msg.arg1 = appid; 5375 msg.arg2 = 0; 5376 Bundle bundle = new Bundle(); 5377 bundle.putString("pkg", pkg); 5378 bundle.putString("reason", reason); 5379 msg.obj = bundle; 5380 mHandler.sendMessage(msg); 5381 } else { 5382 throw new SecurityException(callerUid + " cannot kill pkg: " + 5383 pkg); 5384 } 5385 } 5386 5387 @Override closeSystemDialogs(String reason)5388 public void closeSystemDialogs(String reason) { 5389 enforceNotIsolatedCaller("closeSystemDialogs"); 5390 5391 final int pid = Binder.getCallingPid(); 5392 final int uid = Binder.getCallingUid(); 5393 final long origId = Binder.clearCallingIdentity(); 5394 try { 5395 synchronized (this) { 5396 // Only allow this from foreground processes, so that background 5397 // applications can't abuse it to prevent system UI from being shown. 5398 if (uid >= Process.FIRST_APPLICATION_UID) { 5399 ProcessRecord proc; 5400 synchronized (mPidsSelfLocked) { 5401 proc = mPidsSelfLocked.get(pid); 5402 } 5403 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 5404 Slog.w(TAG, "Ignoring closeSystemDialogs " + reason 5405 + " from background process " + proc); 5406 return; 5407 } 5408 } 5409 closeSystemDialogsLocked(reason); 5410 } 5411 } finally { 5412 Binder.restoreCallingIdentity(origId); 5413 } 5414 } 5415 closeSystemDialogsLocked(String reason)5416 void closeSystemDialogsLocked(String reason) { 5417 Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); 5418 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 5419 | Intent.FLAG_RECEIVER_FOREGROUND); 5420 if (reason != null) { 5421 intent.putExtra("reason", reason); 5422 } 5423 mWindowManager.closeSystemDialogs(reason); 5424 5425 mStackSupervisor.closeSystemDialogsLocked(); 5426 5427 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, null, 5428 AppOpsManager.OP_NONE, null, false, false, 5429 -1, Process.SYSTEM_UID, UserHandle.USER_ALL); 5430 } 5431 5432 @Override getProcessMemoryInfo(int[] pids)5433 public Debug.MemoryInfo[] getProcessMemoryInfo(int[] pids) { 5434 enforceNotIsolatedCaller("getProcessMemoryInfo"); 5435 Debug.MemoryInfo[] infos = new Debug.MemoryInfo[pids.length]; 5436 for (int i=pids.length-1; i>=0; i--) { 5437 ProcessRecord proc; 5438 int oomAdj; 5439 synchronized (this) { 5440 synchronized (mPidsSelfLocked) { 5441 proc = mPidsSelfLocked.get(pids[i]); 5442 oomAdj = proc != null ? proc.setAdj : 0; 5443 } 5444 } 5445 infos[i] = new Debug.MemoryInfo(); 5446 Debug.getMemoryInfo(pids[i], infos[i]); 5447 if (proc != null) { 5448 synchronized (this) { 5449 if (proc.thread != null && proc.setAdj == oomAdj) { 5450 // Record this for posterity if the process has been stable. 5451 proc.baseProcessTracker.addPss(infos[i].getTotalPss(), 5452 infos[i].getTotalUss(), false, proc.pkgList); 5453 } 5454 } 5455 } 5456 } 5457 return infos; 5458 } 5459 5460 @Override getProcessPss(int[] pids)5461 public long[] getProcessPss(int[] pids) { 5462 enforceNotIsolatedCaller("getProcessPss"); 5463 long[] pss = new long[pids.length]; 5464 for (int i=pids.length-1; i>=0; i--) { 5465 ProcessRecord proc; 5466 int oomAdj; 5467 synchronized (this) { 5468 synchronized (mPidsSelfLocked) { 5469 proc = mPidsSelfLocked.get(pids[i]); 5470 oomAdj = proc != null ? proc.setAdj : 0; 5471 } 5472 } 5473 long[] tmpUss = new long[1]; 5474 pss[i] = Debug.getPss(pids[i], tmpUss, null); 5475 if (proc != null) { 5476 synchronized (this) { 5477 if (proc.thread != null && proc.setAdj == oomAdj) { 5478 // Record this for posterity if the process has been stable. 5479 proc.baseProcessTracker.addPss(pss[i], tmpUss[0], false, proc.pkgList); 5480 } 5481 } 5482 } 5483 } 5484 return pss; 5485 } 5486 5487 @Override killApplicationProcess(String processName, int uid)5488 public void killApplicationProcess(String processName, int uid) { 5489 if (processName == null) { 5490 return; 5491 } 5492 5493 int callerUid = Binder.getCallingUid(); 5494 // Only the system server can kill an application 5495 if (callerUid == Process.SYSTEM_UID) { 5496 synchronized (this) { 5497 ProcessRecord app = getProcessRecordLocked(processName, uid, true); 5498 if (app != null && app.thread != null) { 5499 try { 5500 app.thread.scheduleSuicide(); 5501 } catch (RemoteException e) { 5502 // If the other end already died, then our work here is done. 5503 } 5504 } else { 5505 Slog.w(TAG, "Process/uid not found attempting kill of " 5506 + processName + " / " + uid); 5507 } 5508 } 5509 } else { 5510 throw new SecurityException(callerUid + " cannot kill app process: " + 5511 processName); 5512 } 5513 } 5514 forceStopPackageLocked(final String packageName, int uid, String reason)5515 private void forceStopPackageLocked(final String packageName, int uid, String reason) { 5516 forceStopPackageLocked(packageName, UserHandle.getAppId(uid), false, 5517 false, true, false, false, UserHandle.getUserId(uid), reason); 5518 Intent intent = new Intent(Intent.ACTION_PACKAGE_RESTARTED, 5519 Uri.fromParts("package", packageName, null)); 5520 if (!mProcessesReady) { 5521 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 5522 | Intent.FLAG_RECEIVER_FOREGROUND); 5523 } 5524 intent.putExtra(Intent.EXTRA_UID, uid); 5525 intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(uid)); 5526 broadcastIntentLocked(null, null, intent, 5527 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 5528 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.getUserId(uid)); 5529 } 5530 forceStopUserLocked(int userId, String reason)5531 private void forceStopUserLocked(int userId, String reason) { 5532 forceStopPackageLocked(null, -1, false, false, true, false, false, userId, reason); 5533 Intent intent = new Intent(Intent.ACTION_USER_STOPPED); 5534 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 5535 | Intent.FLAG_RECEIVER_FOREGROUND); 5536 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 5537 broadcastIntentLocked(null, null, intent, 5538 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 5539 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 5540 } 5541 killPackageProcessesLocked(String packageName, int appId, int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, boolean doit, boolean evenPersistent, String reason)5542 private final boolean killPackageProcessesLocked(String packageName, int appId, 5543 int userId, int minOomAdj, boolean callerWillRestart, boolean allowRestart, 5544 boolean doit, boolean evenPersistent, String reason) { 5545 ArrayList<ProcessRecord> procs = new ArrayList<>(); 5546 5547 // Remove all processes this package may have touched: all with the 5548 // same UID (except for the system or root user), and all whose name 5549 // matches the package name. 5550 final int NP = mProcessNames.getMap().size(); 5551 for (int ip=0; ip<NP; ip++) { 5552 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 5553 final int NA = apps.size(); 5554 for (int ia=0; ia<NA; ia++) { 5555 ProcessRecord app = apps.valueAt(ia); 5556 if (app.persistent && !evenPersistent) { 5557 // we don't kill persistent processes 5558 continue; 5559 } 5560 if (app.removed) { 5561 if (doit) { 5562 procs.add(app); 5563 } 5564 continue; 5565 } 5566 5567 // Skip process if it doesn't meet our oom adj requirement. 5568 if (app.setAdj < minOomAdj) { 5569 continue; 5570 } 5571 5572 // If no package is specified, we call all processes under the 5573 // give user id. 5574 if (packageName == null) { 5575 if (userId != UserHandle.USER_ALL && app.userId != userId) { 5576 continue; 5577 } 5578 if (appId >= 0 && UserHandle.getAppId(app.uid) != appId) { 5579 continue; 5580 } 5581 // Package has been specified, we want to hit all processes 5582 // that match it. We need to qualify this by the processes 5583 // that are running under the specified app and user ID. 5584 } else { 5585 final boolean isDep = app.pkgDeps != null 5586 && app.pkgDeps.contains(packageName); 5587 if (!isDep && UserHandle.getAppId(app.uid) != appId) { 5588 continue; 5589 } 5590 if (userId != UserHandle.USER_ALL && app.userId != userId) { 5591 continue; 5592 } 5593 if (!app.pkgList.containsKey(packageName) && !isDep) { 5594 continue; 5595 } 5596 } 5597 5598 // Process has passed all conditions, kill it! 5599 if (!doit) { 5600 return true; 5601 } 5602 app.removed = true; 5603 procs.add(app); 5604 } 5605 } 5606 5607 int N = procs.size(); 5608 for (int i=0; i<N; i++) { 5609 removeProcessLocked(procs.get(i), callerWillRestart, allowRestart, reason); 5610 } 5611 updateOomAdjLocked(); 5612 return N > 0; 5613 } 5614 cleanupDisabledPackageComponentsLocked( String packageName, int userId, boolean killProcess, String[] changedClasses)5615 private void cleanupDisabledPackageComponentsLocked( 5616 String packageName, int userId, boolean killProcess, String[] changedClasses) { 5617 5618 Set<String> disabledClasses = null; 5619 boolean packageDisabled = false; 5620 IPackageManager pm = AppGlobals.getPackageManager(); 5621 5622 if (changedClasses == null) { 5623 // Nothing changed... 5624 return; 5625 } 5626 5627 // Determine enable/disable state of the package and its components. 5628 int enabled = PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 5629 for (int i = changedClasses.length - 1; i >= 0; i--) { 5630 final String changedClass = changedClasses[i]; 5631 5632 if (changedClass.equals(packageName)) { 5633 try { 5634 // Entire package setting changed 5635 enabled = pm.getApplicationEnabledSetting(packageName, 5636 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_OWNER); 5637 } catch (Exception e) { 5638 // No such package/component; probably racing with uninstall. In any 5639 // event it means we have nothing further to do here. 5640 return; 5641 } 5642 packageDisabled = enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 5643 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 5644 if (packageDisabled) { 5645 // Entire package is disabled. 5646 // No need to continue to check component states. 5647 disabledClasses = null; 5648 break; 5649 } 5650 } else { 5651 try { 5652 enabled = pm.getComponentEnabledSetting( 5653 new ComponentName(packageName, changedClass), 5654 (userId != UserHandle.USER_ALL) ? userId : UserHandle.USER_OWNER); 5655 } catch (Exception e) { 5656 // As above, probably racing with uninstall. 5657 return; 5658 } 5659 if (enabled != PackageManager.COMPONENT_ENABLED_STATE_ENABLED 5660 && enabled != PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) { 5661 if (disabledClasses == null) { 5662 disabledClasses = new ArraySet<>(changedClasses.length); 5663 } 5664 disabledClasses.add(changedClass); 5665 } 5666 } 5667 } 5668 5669 if (!packageDisabled && disabledClasses == null) { 5670 // Nothing to do here... 5671 return; 5672 } 5673 5674 // Clean-up disabled activities. 5675 if (mStackSupervisor.finishDisabledPackageActivitiesLocked( 5676 packageName, disabledClasses, true, false, userId) && mBooted) { 5677 mStackSupervisor.resumeTopActivitiesLocked(); 5678 mStackSupervisor.scheduleIdleLocked(); 5679 } 5680 5681 // Clean-up disabled tasks 5682 cleanupDisabledPackageTasksLocked(packageName, disabledClasses, userId); 5683 5684 // Clean-up disabled services. 5685 mServices.bringDownDisabledPackageServicesLocked( 5686 packageName, disabledClasses, userId, false, killProcess, true); 5687 5688 // Clean-up disabled providers. 5689 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 5690 mProviderMap.collectPackageProvidersLocked( 5691 packageName, disabledClasses, true, false, userId, providers); 5692 for (int i = providers.size() - 1; i >= 0; i--) { 5693 removeDyingProviderLocked(null, providers.get(i), true); 5694 } 5695 5696 // Clean-up disabled broadcast receivers. 5697 for (int i = mBroadcastQueues.length - 1; i >= 0; i--) { 5698 mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 5699 packageName, disabledClasses, userId, true); 5700 } 5701 5702 } 5703 forceStopPackageLocked(String packageName, int appId, boolean callerWillRestart, boolean purgeCache, boolean doit, boolean evenPersistent, boolean uninstalling, int userId, String reason)5704 private final boolean forceStopPackageLocked(String packageName, int appId, 5705 boolean callerWillRestart, boolean purgeCache, boolean doit, 5706 boolean evenPersistent, boolean uninstalling, int userId, String reason) { 5707 int i; 5708 5709 if (userId == UserHandle.USER_ALL && packageName == null) { 5710 Slog.w(TAG, "Can't force stop all processes of all users, that is insane!"); 5711 } 5712 5713 if (appId < 0 && packageName != null) { 5714 try { 5715 appId = UserHandle.getAppId( 5716 AppGlobals.getPackageManager().getPackageUid(packageName, 0)); 5717 } catch (RemoteException e) { 5718 } 5719 } 5720 5721 if (doit) { 5722 if (packageName != null) { 5723 Slog.i(TAG, "Force stopping " + packageName + " appid=" + appId 5724 + " user=" + userId + ": " + reason); 5725 } else { 5726 Slog.i(TAG, "Force stopping u" + userId + ": " + reason); 5727 } 5728 5729 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap(); 5730 for (int ip = pmap.size() - 1; ip >= 0; ip--) { 5731 SparseArray<Long> ba = pmap.valueAt(ip); 5732 for (i = ba.size() - 1; i >= 0; i--) { 5733 boolean remove = false; 5734 final int entUid = ba.keyAt(i); 5735 if (packageName != null) { 5736 if (userId == UserHandle.USER_ALL) { 5737 if (UserHandle.getAppId(entUid) == appId) { 5738 remove = true; 5739 } 5740 } else { 5741 if (entUid == UserHandle.getUid(userId, appId)) { 5742 remove = true; 5743 } 5744 } 5745 } else if (UserHandle.getUserId(entUid) == userId) { 5746 remove = true; 5747 } 5748 if (remove) { 5749 ba.removeAt(i); 5750 } 5751 } 5752 if (ba.size() == 0) { 5753 pmap.removeAt(ip); 5754 } 5755 } 5756 } 5757 5758 boolean didSomething = killPackageProcessesLocked(packageName, appId, userId, 5759 -100, callerWillRestart, true, doit, evenPersistent, 5760 packageName == null ? ("stop user " + userId) : ("stop " + packageName)); 5761 5762 if (mStackSupervisor.finishDisabledPackageActivitiesLocked( 5763 packageName, null, doit, evenPersistent, userId)) { 5764 if (!doit) { 5765 return true; 5766 } 5767 didSomething = true; 5768 } 5769 5770 if (mServices.bringDownDisabledPackageServicesLocked( 5771 packageName, null, userId, evenPersistent, true, doit)) { 5772 if (!doit) { 5773 return true; 5774 } 5775 didSomething = true; 5776 } 5777 5778 if (packageName == null) { 5779 // Remove all sticky broadcasts from this user. 5780 mStickyBroadcasts.remove(userId); 5781 } 5782 5783 ArrayList<ContentProviderRecord> providers = new ArrayList<>(); 5784 if (mProviderMap.collectPackageProvidersLocked(packageName, null, doit, evenPersistent, 5785 userId, providers)) { 5786 if (!doit) { 5787 return true; 5788 } 5789 didSomething = true; 5790 } 5791 for (i = providers.size() - 1; i >= 0; i--) { 5792 removeDyingProviderLocked(null, providers.get(i), true); 5793 } 5794 5795 // Remove transient permissions granted from/to this package/user 5796 removeUriPermissionsForPackageLocked(packageName, userId, false); 5797 5798 if (doit) { 5799 for (i = mBroadcastQueues.length - 1; i >= 0; i--) { 5800 didSomething |= mBroadcastQueues[i].cleanupDisabledPackageReceiversLocked( 5801 packageName, null, userId, doit); 5802 } 5803 } 5804 5805 if (packageName == null || uninstalling) { 5806 // Remove pending intents. For now we only do this when force 5807 // stopping users, because we have some problems when doing this 5808 // for packages -- app widgets are not currently cleaned up for 5809 // such packages, so they can be left with bad pending intents. 5810 if (mIntentSenderRecords.size() > 0) { 5811 Iterator<WeakReference<PendingIntentRecord>> it 5812 = mIntentSenderRecords.values().iterator(); 5813 while (it.hasNext()) { 5814 WeakReference<PendingIntentRecord> wpir = it.next(); 5815 if (wpir == null) { 5816 it.remove(); 5817 continue; 5818 } 5819 PendingIntentRecord pir = wpir.get(); 5820 if (pir == null) { 5821 it.remove(); 5822 continue; 5823 } 5824 if (packageName == null) { 5825 // Stopping user, remove all objects for the user. 5826 if (pir.key.userId != userId) { 5827 // Not the same user, skip it. 5828 continue; 5829 } 5830 } else { 5831 if (UserHandle.getAppId(pir.uid) != appId) { 5832 // Different app id, skip it. 5833 continue; 5834 } 5835 if (userId != UserHandle.USER_ALL && pir.key.userId != userId) { 5836 // Different user, skip it. 5837 continue; 5838 } 5839 if (!pir.key.packageName.equals(packageName)) { 5840 // Different package, skip it. 5841 continue; 5842 } 5843 } 5844 if (!doit) { 5845 return true; 5846 } 5847 didSomething = true; 5848 it.remove(); 5849 pir.canceled = true; 5850 if (pir.key.activity != null && pir.key.activity.pendingResults != null) { 5851 pir.key.activity.pendingResults.remove(pir.ref); 5852 } 5853 } 5854 } 5855 } 5856 5857 if (doit) { 5858 if (purgeCache && packageName != null) { 5859 AttributeCache ac = AttributeCache.instance(); 5860 if (ac != null) { 5861 ac.removePackage(packageName); 5862 } 5863 } 5864 if (mBooted) { 5865 mStackSupervisor.resumeTopActivitiesLocked(); 5866 mStackSupervisor.scheduleIdleLocked(); 5867 } 5868 } 5869 5870 return didSomething; 5871 } 5872 removeProcessNameLocked(final String name, final int uid)5873 private final ProcessRecord removeProcessNameLocked(final String name, final int uid) { 5874 ProcessRecord old = mProcessNames.remove(name, uid); 5875 if (old != null) { 5876 old.uidRecord.numProcs--; 5877 if (old.uidRecord.numProcs == 0) { 5878 // No more processes using this uid, tell clients it is gone. 5879 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 5880 "No more processes in " + old.uidRecord); 5881 enqueueUidChangeLocked(old.uidRecord, true); 5882 mActiveUids.remove(uid); 5883 } 5884 old.uidRecord = null; 5885 } 5886 mIsolatedProcesses.remove(uid); 5887 return old; 5888 } 5889 addProcessNameLocked(ProcessRecord proc)5890 private final void addProcessNameLocked(ProcessRecord proc) { 5891 // We shouldn't already have a process under this name, but just in case we 5892 // need to clean up whatever may be there now. 5893 ProcessRecord old = removeProcessNameLocked(proc.processName, proc.uid); 5894 if (old == proc && proc.persistent) { 5895 // We are re-adding a persistent process. Whatevs! Just leave it there. 5896 Slog.w(TAG, "Re-adding persistent process " + proc); 5897 } else if (old != null) { 5898 Slog.wtf(TAG, "Already have existing proc " + old + " when adding " + proc); 5899 } 5900 UidRecord uidRec = mActiveUids.get(proc.uid); 5901 if (uidRec == null) { 5902 uidRec = new UidRecord(proc.uid); 5903 // This is the first appearance of the uid, report it now! 5904 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 5905 "Creating new process uid: " + uidRec); 5906 mActiveUids.put(proc.uid, uidRec); 5907 enqueueUidChangeLocked(uidRec, false); 5908 } 5909 proc.uidRecord = uidRec; 5910 uidRec.numProcs++; 5911 mProcessNames.put(proc.processName, proc.uid, proc); 5912 if (proc.isolated) { 5913 mIsolatedProcesses.put(proc.uid, proc); 5914 } 5915 } 5916 removeProcessLocked(ProcessRecord app, boolean callerWillRestart, boolean allowRestart, String reason)5917 private final boolean removeProcessLocked(ProcessRecord app, 5918 boolean callerWillRestart, boolean allowRestart, String reason) { 5919 final String name = app.processName; 5920 final int uid = app.uid; 5921 if (DEBUG_PROCESSES) Slog.d(TAG_PROCESSES, 5922 "Force removing proc " + app.toShortString() + " (" + name + "/" + uid + ")"); 5923 5924 removeProcessNameLocked(name, uid); 5925 if (mHeavyWeightProcess == app) { 5926 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 5927 mHeavyWeightProcess.userId, 0)); 5928 mHeavyWeightProcess = null; 5929 } 5930 boolean needRestart = false; 5931 if (app.pid > 0 && app.pid != MY_PID) { 5932 int pid = app.pid; 5933 synchronized (mPidsSelfLocked) { 5934 mPidsSelfLocked.remove(pid); 5935 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 5936 } 5937 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 5938 if (app.isolated) { 5939 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 5940 } 5941 boolean willRestart = false; 5942 if (app.persistent && !app.isolated) { 5943 if (!callerWillRestart) { 5944 willRestart = true; 5945 } else { 5946 needRestart = true; 5947 } 5948 } 5949 app.kill(reason, true); 5950 handleAppDiedLocked(app, willRestart, allowRestart); 5951 if (willRestart) { 5952 removeLruProcessLocked(app); 5953 addAppLocked(app.info, false, null /* ABI override */); 5954 } 5955 } else { 5956 mRemovedProcesses.add(app); 5957 } 5958 5959 return needRestart; 5960 } 5961 processContentProviderPublishTimedOutLocked(ProcessRecord app)5962 private final void processContentProviderPublishTimedOutLocked(ProcessRecord app) { 5963 cleanupAppInLaunchingProvidersLocked(app, true); 5964 removeProcessLocked(app, false, true, "timeout publishing content providers"); 5965 } 5966 processStartTimedOutLocked(ProcessRecord app)5967 private final void processStartTimedOutLocked(ProcessRecord app) { 5968 final int pid = app.pid; 5969 boolean gone = false; 5970 synchronized (mPidsSelfLocked) { 5971 ProcessRecord knownApp = mPidsSelfLocked.get(pid); 5972 if (knownApp != null && knownApp.thread == null) { 5973 mPidsSelfLocked.remove(pid); 5974 gone = true; 5975 } 5976 } 5977 5978 if (gone) { 5979 Slog.w(TAG, "Process " + app + " failed to attach"); 5980 EventLog.writeEvent(EventLogTags.AM_PROCESS_START_TIMEOUT, app.userId, 5981 pid, app.uid, app.processName); 5982 removeProcessNameLocked(app.processName, app.uid); 5983 if (mHeavyWeightProcess == app) { 5984 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 5985 mHeavyWeightProcess.userId, 0)); 5986 mHeavyWeightProcess = null; 5987 } 5988 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 5989 if (app.isolated) { 5990 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 5991 } 5992 // Take care of any launching providers waiting for this process. 5993 cleanupAppInLaunchingProvidersLocked(app, true); 5994 // Take care of any services that are waiting for the process. 5995 mServices.processStartTimedOutLocked(app); 5996 app.kill("start timeout", true); 5997 removeLruProcessLocked(app); 5998 if (mBackupTarget != null && mBackupTarget.app.pid == pid) { 5999 Slog.w(TAG, "Unattached app died before backup, skipping"); 6000 try { 6001 IBackupManager bm = IBackupManager.Stub.asInterface( 6002 ServiceManager.getService(Context.BACKUP_SERVICE)); 6003 bm.agentDisconnected(app.info.packageName); 6004 } catch (RemoteException e) { 6005 // Can't happen; the backup manager is local 6006 } 6007 } 6008 if (isPendingBroadcastProcessLocked(pid)) { 6009 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 6010 skipPendingBroadcastLocked(pid); 6011 } 6012 } else { 6013 Slog.w(TAG, "Spurious process start timeout - pid not known for " + app); 6014 } 6015 } 6016 attachApplicationLocked(IApplicationThread thread, int pid)6017 private final boolean attachApplicationLocked(IApplicationThread thread, 6018 int pid) { 6019 6020 // Find the application record that is being attached... either via 6021 // the pid if we are running in multiple processes, or just pull the 6022 // next app record if we are emulating process with anonymous threads. 6023 ProcessRecord app; 6024 if (pid != MY_PID && pid >= 0) { 6025 synchronized (mPidsSelfLocked) { 6026 app = mPidsSelfLocked.get(pid); 6027 } 6028 } else { 6029 app = null; 6030 } 6031 6032 if (app == null) { 6033 Slog.w(TAG, "No pending application record for pid " + pid 6034 + " (IApplicationThread " + thread + "); dropping process"); 6035 EventLog.writeEvent(EventLogTags.AM_DROP_PROCESS, pid); 6036 if (pid > 0 && pid != MY_PID) { 6037 Process.killProcessQuiet(pid); 6038 //TODO: killProcessGroup(app.info.uid, pid); 6039 } else { 6040 try { 6041 thread.scheduleExit(); 6042 } catch (Exception e) { 6043 // Ignore exceptions. 6044 } 6045 } 6046 return false; 6047 } 6048 6049 // If this application record is still attached to a previous 6050 // process, clean it up now. 6051 if (app.thread != null) { 6052 handleAppDiedLocked(app, true, true); 6053 } 6054 6055 // Tell the process all about itself. 6056 6057 if (DEBUG_ALL) Slog.v( 6058 TAG, "Binding process pid " + pid + " to record " + app); 6059 6060 final String processName = app.processName; 6061 try { 6062 AppDeathRecipient adr = new AppDeathRecipient( 6063 app, pid, thread); 6064 thread.asBinder().linkToDeath(adr, 0); 6065 app.deathRecipient = adr; 6066 } catch (RemoteException e) { 6067 app.resetPackageList(mProcessStats); 6068 startProcessLocked(app, "link fail", processName); 6069 return false; 6070 } 6071 6072 EventLog.writeEvent(EventLogTags.AM_PROC_BOUND, app.userId, app.pid, app.processName); 6073 6074 app.makeActive(thread, mProcessStats); 6075 app.curAdj = app.setAdj = -100; 6076 app.curSchedGroup = app.setSchedGroup = Process.THREAD_GROUP_DEFAULT; 6077 app.forcingToForeground = null; 6078 updateProcessForegroundLocked(app, false, false); 6079 app.hasShownUi = false; 6080 app.debugging = false; 6081 app.cached = false; 6082 app.killedByAm = false; 6083 6084 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 6085 6086 boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); 6087 List<ProviderInfo> providers = normalMode ? generateApplicationProvidersLocked(app) : null; 6088 6089 if (providers != null && checkAppInLaunchingProvidersLocked(app)) { 6090 Message msg = mHandler.obtainMessage(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG); 6091 msg.obj = app; 6092 mHandler.sendMessageDelayed(msg, CONTENT_PROVIDER_PUBLISH_TIMEOUT); 6093 } 6094 6095 if (!normalMode) { 6096 Slog.i(TAG, "Launching preboot mode app: " + app); 6097 } 6098 6099 if (DEBUG_ALL) Slog.v( 6100 TAG, "New app record " + app 6101 + " thread=" + thread.asBinder() + " pid=" + pid); 6102 try { 6103 int testMode = IApplicationThread.DEBUG_OFF; 6104 if (mDebugApp != null && mDebugApp.equals(processName)) { 6105 testMode = mWaitForDebugger 6106 ? IApplicationThread.DEBUG_WAIT 6107 : IApplicationThread.DEBUG_ON; 6108 app.debugging = true; 6109 if (mDebugTransient) { 6110 mDebugApp = mOrigDebugApp; 6111 mWaitForDebugger = mOrigWaitForDebugger; 6112 } 6113 } 6114 String profileFile = app.instrumentationProfileFile; 6115 ParcelFileDescriptor profileFd = null; 6116 int samplingInterval = 0; 6117 boolean profileAutoStop = false; 6118 if (mProfileApp != null && mProfileApp.equals(processName)) { 6119 mProfileProc = app; 6120 profileFile = mProfileFile; 6121 profileFd = mProfileFd; 6122 samplingInterval = mSamplingInterval; 6123 profileAutoStop = mAutoStopProfiler; 6124 } 6125 boolean enableOpenGlTrace = false; 6126 if (mOpenGlTraceApp != null && mOpenGlTraceApp.equals(processName)) { 6127 enableOpenGlTrace = true; 6128 mOpenGlTraceApp = null; 6129 } 6130 6131 // If the app is being launched for restore or full backup, set it up specially 6132 boolean isRestrictedBackupMode = false; 6133 if (mBackupTarget != null && mBackupAppName.equals(processName)) { 6134 isRestrictedBackupMode = (mBackupTarget.backupMode == BackupRecord.RESTORE) 6135 || (mBackupTarget.backupMode == BackupRecord.RESTORE_FULL) 6136 || (mBackupTarget.backupMode == BackupRecord.BACKUP_FULL); 6137 } 6138 6139 ensurePackageDexOpt(app.instrumentationInfo != null 6140 ? app.instrumentationInfo.packageName 6141 : app.info.packageName); 6142 if (app.instrumentationClass != null) { 6143 ensurePackageDexOpt(app.instrumentationClass.getPackageName()); 6144 } 6145 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Binding proc " 6146 + processName + " with config " + mConfiguration); 6147 ApplicationInfo appInfo = app.instrumentationInfo != null 6148 ? app.instrumentationInfo : app.info; 6149 app.compat = compatibilityInfoForPackageLocked(appInfo); 6150 if (profileFd != null) { 6151 profileFd = profileFd.dup(); 6152 } 6153 ProfilerInfo profilerInfo = profileFile == null ? null 6154 : new ProfilerInfo(profileFile, profileFd, samplingInterval, profileAutoStop); 6155 thread.bindApplication(processName, appInfo, providers, app.instrumentationClass, 6156 profilerInfo, app.instrumentationArguments, app.instrumentationWatcher, 6157 app.instrumentationUiAutomationConnection, testMode, enableOpenGlTrace, 6158 isRestrictedBackupMode || !normalMode, app.persistent, 6159 new Configuration(mConfiguration), app.compat, 6160 getCommonServicesLocked(app.isolated), 6161 mCoreSettingsObserver.getCoreSettingsLocked()); 6162 updateLruProcessLocked(app, false, null); 6163 app.lastRequestedGc = app.lastLowMemory = SystemClock.uptimeMillis(); 6164 } catch (Exception e) { 6165 // todo: Yikes! What should we do? For now we will try to 6166 // start another process, but that could easily get us in 6167 // an infinite loop of restarting processes... 6168 Slog.wtf(TAG, "Exception thrown during bind of " + app, e); 6169 6170 app.resetPackageList(mProcessStats); 6171 app.unlinkDeathRecipient(); 6172 startProcessLocked(app, "bind fail", processName); 6173 return false; 6174 } 6175 6176 // Remove this record from the list of starting applications. 6177 mPersistentStartingProcesses.remove(app); 6178 if (DEBUG_PROCESSES && mProcessesOnHold.contains(app)) Slog.v(TAG_PROCESSES, 6179 "Attach application locked removing on hold: " + app); 6180 mProcessesOnHold.remove(app); 6181 6182 boolean badApp = false; 6183 boolean didSomething = false; 6184 6185 // See if the top visible activity is waiting to run in this process... 6186 if (normalMode) { 6187 try { 6188 if (mStackSupervisor.attachApplicationLocked(app)) { 6189 didSomething = true; 6190 } 6191 } catch (Exception e) { 6192 Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); 6193 badApp = true; 6194 } 6195 } 6196 6197 // Find any services that should be running in this process... 6198 if (!badApp) { 6199 try { 6200 didSomething |= mServices.attachApplicationLocked(app, processName); 6201 } catch (Exception e) { 6202 Slog.wtf(TAG, "Exception thrown starting services in " + app, e); 6203 badApp = true; 6204 } 6205 } 6206 6207 // Check if a next-broadcast receiver is in this process... 6208 if (!badApp && isPendingBroadcastProcessLocked(pid)) { 6209 try { 6210 didSomething |= sendPendingBroadcastsLocked(app); 6211 } catch (Exception e) { 6212 // If the app died trying to launch the receiver we declare it 'bad' 6213 Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e); 6214 badApp = true; 6215 } 6216 } 6217 6218 // Check whether the next backup agent is in this process... 6219 if (!badApp && mBackupTarget != null && mBackupTarget.appInfo.uid == app.uid) { 6220 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, 6221 "New app is backup target, launching agent for " + app); 6222 ensurePackageDexOpt(mBackupTarget.appInfo.packageName); 6223 try { 6224 thread.scheduleCreateBackupAgent(mBackupTarget.appInfo, 6225 compatibilityInfoForPackageLocked(mBackupTarget.appInfo), 6226 mBackupTarget.backupMode); 6227 } catch (Exception e) { 6228 Slog.wtf(TAG, "Exception thrown creating backup agent in " + app, e); 6229 badApp = true; 6230 } 6231 } 6232 6233 if (badApp) { 6234 app.kill("error during init", true); 6235 handleAppDiedLocked(app, false, true); 6236 return false; 6237 } 6238 6239 if (!didSomething) { 6240 updateOomAdjLocked(); 6241 } 6242 6243 return true; 6244 } 6245 6246 @Override attachApplication(IApplicationThread thread)6247 public final void attachApplication(IApplicationThread thread) { 6248 synchronized (this) { 6249 int callingPid = Binder.getCallingPid(); 6250 final long origId = Binder.clearCallingIdentity(); 6251 attachApplicationLocked(thread, callingPid); 6252 Binder.restoreCallingIdentity(origId); 6253 } 6254 } 6255 6256 @Override activityIdle(IBinder token, Configuration config, boolean stopProfiling)6257 public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) { 6258 final long origId = Binder.clearCallingIdentity(); 6259 synchronized (this) { 6260 ActivityStack stack = ActivityRecord.getStackLocked(token); 6261 if (stack != null) { 6262 ActivityRecord r = 6263 mStackSupervisor.activityIdleInternalLocked(token, false, config); 6264 if (stopProfiling) { 6265 if ((mProfileProc == r.app) && (mProfileFd != null)) { 6266 try { 6267 mProfileFd.close(); 6268 } catch (IOException e) { 6269 } 6270 clearProfilerLocked(); 6271 } 6272 } 6273 } 6274 } 6275 Binder.restoreCallingIdentity(origId); 6276 } 6277 postFinishBooting(boolean finishBooting, boolean enableScreen)6278 void postFinishBooting(boolean finishBooting, boolean enableScreen) { 6279 mHandler.sendMessage(mHandler.obtainMessage(FINISH_BOOTING_MSG, 6280 finishBooting ? 1 : 0, enableScreen ? 1 : 0)); 6281 } 6282 enableScreenAfterBoot()6283 void enableScreenAfterBoot() { 6284 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_ENABLE_SCREEN, 6285 SystemClock.uptimeMillis()); 6286 mWindowManager.enableScreenAfterBoot(); 6287 6288 synchronized (this) { 6289 updateEventDispatchingLocked(); 6290 } 6291 } 6292 6293 @Override showBootMessage(final CharSequence msg, final boolean always)6294 public void showBootMessage(final CharSequence msg, final boolean always) { 6295 if (Binder.getCallingUid() != Process.myUid()) { 6296 // These days only the core system can call this, so apps can't get in 6297 // the way of what we show about running them. 6298 } 6299 mWindowManager.showBootMessage(msg, always); 6300 } 6301 6302 @Override keyguardWaitingForActivityDrawn()6303 public void keyguardWaitingForActivityDrawn() { 6304 enforceNotIsolatedCaller("keyguardWaitingForActivityDrawn"); 6305 final long token = Binder.clearCallingIdentity(); 6306 try { 6307 synchronized (this) { 6308 if (DEBUG_LOCKSCREEN) logLockScreen(""); 6309 mWindowManager.keyguardWaitingForActivityDrawn(); 6310 if (mLockScreenShown == LOCK_SCREEN_SHOWN) { 6311 mLockScreenShown = LOCK_SCREEN_LEAVING; 6312 updateSleepIfNeededLocked(); 6313 } 6314 } 6315 } finally { 6316 Binder.restoreCallingIdentity(token); 6317 } 6318 } 6319 6320 @Override keyguardGoingAway(boolean disableWindowAnimations, boolean keyguardGoingToNotificationShade)6321 public void keyguardGoingAway(boolean disableWindowAnimations, 6322 boolean keyguardGoingToNotificationShade) { 6323 enforceNotIsolatedCaller("keyguardGoingAway"); 6324 final long token = Binder.clearCallingIdentity(); 6325 try { 6326 synchronized (this) { 6327 if (DEBUG_LOCKSCREEN) logLockScreen(""); 6328 mWindowManager.keyguardGoingAway(disableWindowAnimations, 6329 keyguardGoingToNotificationShade); 6330 if (mLockScreenShown == LOCK_SCREEN_SHOWN) { 6331 mLockScreenShown = LOCK_SCREEN_HIDDEN; 6332 updateSleepIfNeededLocked(); 6333 } 6334 } 6335 } finally { 6336 Binder.restoreCallingIdentity(token); 6337 } 6338 } 6339 finishBooting()6340 final void finishBooting() { 6341 synchronized (this) { 6342 if (!mBootAnimationComplete) { 6343 mCallFinishBooting = true; 6344 return; 6345 } 6346 mCallFinishBooting = false; 6347 } 6348 6349 ArraySet<String> completedIsas = new ArraySet<String>(); 6350 for (String abi : Build.SUPPORTED_ABIS) { 6351 Process.establishZygoteConnectionForAbi(abi); 6352 final String instructionSet = VMRuntime.getInstructionSet(abi); 6353 if (!completedIsas.contains(instructionSet)) { 6354 if (mInstaller.markBootComplete(VMRuntime.getInstructionSet(abi)) != 0) { 6355 Slog.e(TAG, "Unable to mark boot complete for abi: " + abi); 6356 } 6357 completedIsas.add(instructionSet); 6358 } 6359 } 6360 6361 IntentFilter pkgFilter = new IntentFilter(); 6362 pkgFilter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART); 6363 pkgFilter.addDataScheme("package"); 6364 mContext.registerReceiver(new BroadcastReceiver() { 6365 @Override 6366 public void onReceive(Context context, Intent intent) { 6367 String[] pkgs = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES); 6368 if (pkgs != null) { 6369 for (String pkg : pkgs) { 6370 synchronized (ActivityManagerService.this) { 6371 if (forceStopPackageLocked(pkg, -1, false, false, false, false, false, 6372 0, "query restart")) { 6373 setResultCode(Activity.RESULT_OK); 6374 return; 6375 } 6376 } 6377 } 6378 } 6379 } 6380 }, pkgFilter); 6381 6382 IntentFilter dumpheapFilter = new IntentFilter(); 6383 dumpheapFilter.addAction(DumpHeapActivity.ACTION_DELETE_DUMPHEAP); 6384 mContext.registerReceiver(new BroadcastReceiver() { 6385 @Override 6386 public void onReceive(Context context, Intent intent) { 6387 if (intent.getBooleanExtra(DumpHeapActivity.EXTRA_DELAY_DELETE, false)) { 6388 mHandler.sendEmptyMessageDelayed(POST_DUMP_HEAP_NOTIFICATION_MSG, 5*60*1000); 6389 } else { 6390 mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG); 6391 } 6392 } 6393 }, dumpheapFilter); 6394 6395 // Let system services know. 6396 mSystemServiceManager.startBootPhase(SystemService.PHASE_BOOT_COMPLETED); 6397 6398 synchronized (this) { 6399 // Ensure that any processes we had put on hold are now started 6400 // up. 6401 final int NP = mProcessesOnHold.size(); 6402 if (NP > 0) { 6403 ArrayList<ProcessRecord> procs = 6404 new ArrayList<ProcessRecord>(mProcessesOnHold); 6405 for (int ip=0; ip<NP; ip++) { 6406 if (DEBUG_PROCESSES) Slog.v(TAG_PROCESSES, "Starting process on hold: " 6407 + procs.get(ip)); 6408 startProcessLocked(procs.get(ip), "on-hold", null); 6409 } 6410 } 6411 6412 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 6413 // Start looking for apps that are abusing wake locks. 6414 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 6415 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 6416 // Tell anyone interested that we are done booting! 6417 SystemProperties.set("sys.boot_completed", "1"); 6418 6419 // And trigger dev.bootcomplete if we are not showing encryption progress 6420 if (!"trigger_restart_min_framework".equals(SystemProperties.get("vold.decrypt")) 6421 || "".equals(SystemProperties.get("vold.encrypt_progress"))) { 6422 SystemProperties.set("dev.bootcomplete", "1"); 6423 } 6424 for (int i=0; i<mStartedUsers.size(); i++) { 6425 UserState uss = mStartedUsers.valueAt(i); 6426 if (uss.mState == UserState.STATE_BOOTING) { 6427 uss.mState = UserState.STATE_RUNNING; 6428 final int userId = mStartedUsers.keyAt(i); 6429 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 6430 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 6431 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT); 6432 broadcastIntentLocked(null, null, intent, null, 6433 new IIntentReceiver.Stub() { 6434 @Override 6435 public void performReceive(Intent intent, int resultCode, 6436 String data, Bundle extras, boolean ordered, 6437 boolean sticky, int sendingUser) { 6438 synchronized (ActivityManagerService.this) { 6439 requestPssAllProcsLocked(SystemClock.uptimeMillis(), 6440 true, false); 6441 } 6442 } 6443 }, 6444 0, null, null, 6445 new String[] {android.Manifest.permission.RECEIVE_BOOT_COMPLETED}, 6446 AppOpsManager.OP_NONE, null, true, false, 6447 MY_PID, Process.SYSTEM_UID, userId); 6448 } 6449 } 6450 scheduleStartProfilesLocked(); 6451 } 6452 } 6453 } 6454 6455 @Override bootAnimationComplete()6456 public void bootAnimationComplete() { 6457 final boolean callFinishBooting; 6458 synchronized (this) { 6459 callFinishBooting = mCallFinishBooting; 6460 mBootAnimationComplete = true; 6461 } 6462 if (callFinishBooting) { 6463 finishBooting(); 6464 } 6465 } 6466 ensureBootCompleted()6467 final void ensureBootCompleted() { 6468 boolean booting; 6469 boolean enableScreen; 6470 synchronized (this) { 6471 booting = mBooting; 6472 mBooting = false; 6473 enableScreen = !mBooted; 6474 mBooted = true; 6475 } 6476 6477 if (booting) { 6478 finishBooting(); 6479 } 6480 6481 if (enableScreen) { 6482 enableScreenAfterBoot(); 6483 } 6484 } 6485 6486 @Override activityResumed(IBinder token)6487 public final void activityResumed(IBinder token) { 6488 final long origId = Binder.clearCallingIdentity(); 6489 synchronized(this) { 6490 ActivityStack stack = ActivityRecord.getStackLocked(token); 6491 if (stack != null) { 6492 ActivityRecord.activityResumedLocked(token); 6493 } 6494 } 6495 Binder.restoreCallingIdentity(origId); 6496 } 6497 6498 @Override activityPaused(IBinder token)6499 public final void activityPaused(IBinder token) { 6500 final long origId = Binder.clearCallingIdentity(); 6501 synchronized(this) { 6502 ActivityStack stack = ActivityRecord.getStackLocked(token); 6503 if (stack != null) { 6504 stack.activityPausedLocked(token, false); 6505 } 6506 } 6507 Binder.restoreCallingIdentity(origId); 6508 } 6509 6510 @Override activityStopped(IBinder token, Bundle icicle, PersistableBundle persistentState, CharSequence description)6511 public final void activityStopped(IBinder token, Bundle icicle, 6512 PersistableBundle persistentState, CharSequence description) { 6513 if (DEBUG_ALL) Slog.v(TAG, "Activity stopped: token=" + token); 6514 6515 // Refuse possible leaked file descriptors 6516 if (icicle != null && icicle.hasFileDescriptors()) { 6517 throw new IllegalArgumentException("File descriptors passed in Bundle"); 6518 } 6519 6520 final long origId = Binder.clearCallingIdentity(); 6521 6522 synchronized (this) { 6523 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6524 if (r != null) { 6525 r.task.stack.activityStoppedLocked(r, icicle, persistentState, description); 6526 } 6527 } 6528 6529 trimApplications(); 6530 6531 Binder.restoreCallingIdentity(origId); 6532 } 6533 6534 @Override activityDestroyed(IBinder token)6535 public final void activityDestroyed(IBinder token) { 6536 if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "ACTIVITY DESTROYED: " + token); 6537 synchronized (this) { 6538 ActivityStack stack = ActivityRecord.getStackLocked(token); 6539 if (stack != null) { 6540 stack.activityDestroyedLocked(token, "activityDestroyed"); 6541 } 6542 } 6543 } 6544 6545 @Override backgroundResourcesReleased(IBinder token)6546 public final void backgroundResourcesReleased(IBinder token) { 6547 final long origId = Binder.clearCallingIdentity(); 6548 try { 6549 synchronized (this) { 6550 ActivityStack stack = ActivityRecord.getStackLocked(token); 6551 if (stack != null) { 6552 stack.backgroundResourcesReleased(); 6553 } 6554 } 6555 } finally { 6556 Binder.restoreCallingIdentity(origId); 6557 } 6558 } 6559 6560 @Override notifyLaunchTaskBehindComplete(IBinder token)6561 public final void notifyLaunchTaskBehindComplete(IBinder token) { 6562 mStackSupervisor.scheduleLaunchTaskBehindComplete(token); 6563 } 6564 6565 @Override notifyEnterAnimationComplete(IBinder token)6566 public final void notifyEnterAnimationComplete(IBinder token) { 6567 mHandler.sendMessage(mHandler.obtainMessage(ENTER_ANIMATION_COMPLETE_MSG, token)); 6568 } 6569 6570 @Override getCallingPackage(IBinder token)6571 public String getCallingPackage(IBinder token) { 6572 synchronized (this) { 6573 ActivityRecord r = getCallingRecordLocked(token); 6574 return r != null ? r.info.packageName : null; 6575 } 6576 } 6577 6578 @Override getCallingActivity(IBinder token)6579 public ComponentName getCallingActivity(IBinder token) { 6580 synchronized (this) { 6581 ActivityRecord r = getCallingRecordLocked(token); 6582 return r != null ? r.intent.getComponent() : null; 6583 } 6584 } 6585 getCallingRecordLocked(IBinder token)6586 private ActivityRecord getCallingRecordLocked(IBinder token) { 6587 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6588 if (r == null) { 6589 return null; 6590 } 6591 return r.resultTo; 6592 } 6593 6594 @Override getActivityClassForToken(IBinder token)6595 public ComponentName getActivityClassForToken(IBinder token) { 6596 synchronized(this) { 6597 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6598 if (r == null) { 6599 return null; 6600 } 6601 return r.intent.getComponent(); 6602 } 6603 } 6604 6605 @Override getPackageForToken(IBinder token)6606 public String getPackageForToken(IBinder token) { 6607 synchronized(this) { 6608 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6609 if (r == null) { 6610 return null; 6611 } 6612 return r.packageName; 6613 } 6614 } 6615 6616 @Override isRootVoiceInteraction(IBinder token)6617 public boolean isRootVoiceInteraction(IBinder token) { 6618 synchronized(this) { 6619 ActivityRecord r = ActivityRecord.isInStackLocked(token); 6620 if (r == null) { 6621 return false; 6622 } 6623 return r.rootVoiceInteraction; 6624 } 6625 } 6626 6627 @Override getIntentSender(int type, String packageName, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle options, int userId)6628 public IIntentSender getIntentSender(int type, 6629 String packageName, IBinder token, String resultWho, 6630 int requestCode, Intent[] intents, String[] resolvedTypes, 6631 int flags, Bundle options, int userId) { 6632 enforceNotIsolatedCaller("getIntentSender"); 6633 // Refuse possible leaked file descriptors 6634 if (intents != null) { 6635 if (intents.length < 1) { 6636 throw new IllegalArgumentException("Intents array length must be >= 1"); 6637 } 6638 for (int i=0; i<intents.length; i++) { 6639 Intent intent = intents[i]; 6640 if (intent != null) { 6641 if (intent.hasFileDescriptors()) { 6642 throw new IllegalArgumentException("File descriptors passed in Intent"); 6643 } 6644 if (type == ActivityManager.INTENT_SENDER_BROADCAST && 6645 (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 6646 throw new IllegalArgumentException( 6647 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 6648 } 6649 intents[i] = new Intent(intent); 6650 } 6651 } 6652 if (resolvedTypes != null && resolvedTypes.length != intents.length) { 6653 throw new IllegalArgumentException( 6654 "Intent array length does not match resolvedTypes length"); 6655 } 6656 } 6657 if (options != null) { 6658 if (options.hasFileDescriptors()) { 6659 throw new IllegalArgumentException("File descriptors passed in options"); 6660 } 6661 } 6662 6663 synchronized(this) { 6664 int callingUid = Binder.getCallingUid(); 6665 int origUserId = userId; 6666 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 6667 type == ActivityManager.INTENT_SENDER_BROADCAST, 6668 ALLOW_NON_FULL, "getIntentSender", null); 6669 if (origUserId == UserHandle.USER_CURRENT) { 6670 // We don't want to evaluate this until the pending intent is 6671 // actually executed. However, we do want to always do the 6672 // security checking for it above. 6673 userId = UserHandle.USER_CURRENT; 6674 } 6675 try { 6676 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 6677 int uid = AppGlobals.getPackageManager() 6678 .getPackageUid(packageName, UserHandle.getUserId(callingUid)); 6679 if (!UserHandle.isSameApp(callingUid, uid)) { 6680 String msg = "Permission Denial: getIntentSender() from pid=" 6681 + Binder.getCallingPid() 6682 + ", uid=" + Binder.getCallingUid() 6683 + ", (need uid=" + uid + ")" 6684 + " is not allowed to send as package " + packageName; 6685 Slog.w(TAG, msg); 6686 throw new SecurityException(msg); 6687 } 6688 } 6689 6690 return getIntentSenderLocked(type, packageName, callingUid, userId, 6691 token, resultWho, requestCode, intents, resolvedTypes, flags, options); 6692 6693 } catch (RemoteException e) { 6694 throw new SecurityException(e); 6695 } 6696 } 6697 } 6698 getIntentSenderLocked(int type, String packageName, int callingUid, int userId, IBinder token, String resultWho, int requestCode, Intent[] intents, String[] resolvedTypes, int flags, Bundle options)6699 IIntentSender getIntentSenderLocked(int type, String packageName, 6700 int callingUid, int userId, IBinder token, String resultWho, 6701 int requestCode, Intent[] intents, String[] resolvedTypes, int flags, 6702 Bundle options) { 6703 if (DEBUG_MU) Slog.v(TAG_MU, "getIntentSenderLocked(): uid=" + callingUid); 6704 ActivityRecord activity = null; 6705 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 6706 activity = ActivityRecord.isInStackLocked(token); 6707 if (activity == null) { 6708 return null; 6709 } 6710 if (activity.finishing) { 6711 return null; 6712 } 6713 } 6714 6715 final boolean noCreate = (flags&PendingIntent.FLAG_NO_CREATE) != 0; 6716 final boolean cancelCurrent = (flags&PendingIntent.FLAG_CANCEL_CURRENT) != 0; 6717 final boolean updateCurrent = (flags&PendingIntent.FLAG_UPDATE_CURRENT) != 0; 6718 flags &= ~(PendingIntent.FLAG_NO_CREATE|PendingIntent.FLAG_CANCEL_CURRENT 6719 |PendingIntent.FLAG_UPDATE_CURRENT); 6720 6721 PendingIntentRecord.Key key = new PendingIntentRecord.Key( 6722 type, packageName, activity, resultWho, 6723 requestCode, intents, resolvedTypes, flags, options, userId); 6724 WeakReference<PendingIntentRecord> ref; 6725 ref = mIntentSenderRecords.get(key); 6726 PendingIntentRecord rec = ref != null ? ref.get() : null; 6727 if (rec != null) { 6728 if (!cancelCurrent) { 6729 if (updateCurrent) { 6730 if (rec.key.requestIntent != null) { 6731 rec.key.requestIntent.replaceExtras(intents != null ? 6732 intents[intents.length - 1] : null); 6733 } 6734 if (intents != null) { 6735 intents[intents.length-1] = rec.key.requestIntent; 6736 rec.key.allIntents = intents; 6737 rec.key.allResolvedTypes = resolvedTypes; 6738 } else { 6739 rec.key.allIntents = null; 6740 rec.key.allResolvedTypes = null; 6741 } 6742 } 6743 return rec; 6744 } 6745 rec.canceled = true; 6746 mIntentSenderRecords.remove(key); 6747 } 6748 if (noCreate) { 6749 return rec; 6750 } 6751 rec = new PendingIntentRecord(this, key, callingUid); 6752 mIntentSenderRecords.put(key, rec.ref); 6753 if (type == ActivityManager.INTENT_SENDER_ACTIVITY_RESULT) { 6754 if (activity.pendingResults == null) { 6755 activity.pendingResults 6756 = new HashSet<WeakReference<PendingIntentRecord>>(); 6757 } 6758 activity.pendingResults.add(rec.ref); 6759 } 6760 return rec; 6761 } 6762 6763 @Override cancelIntentSender(IIntentSender sender)6764 public void cancelIntentSender(IIntentSender sender) { 6765 if (!(sender instanceof PendingIntentRecord)) { 6766 return; 6767 } 6768 synchronized(this) { 6769 PendingIntentRecord rec = (PendingIntentRecord)sender; 6770 try { 6771 int uid = AppGlobals.getPackageManager() 6772 .getPackageUid(rec.key.packageName, UserHandle.getCallingUserId()); 6773 if (!UserHandle.isSameApp(uid, Binder.getCallingUid())) { 6774 String msg = "Permission Denial: cancelIntentSender() from pid=" 6775 + Binder.getCallingPid() 6776 + ", uid=" + Binder.getCallingUid() 6777 + " is not allowed to cancel packges " 6778 + rec.key.packageName; 6779 Slog.w(TAG, msg); 6780 throw new SecurityException(msg); 6781 } 6782 } catch (RemoteException e) { 6783 throw new SecurityException(e); 6784 } 6785 cancelIntentSenderLocked(rec, true); 6786 } 6787 } 6788 cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity)6789 void cancelIntentSenderLocked(PendingIntentRecord rec, boolean cleanActivity) { 6790 rec.canceled = true; 6791 mIntentSenderRecords.remove(rec.key); 6792 if (cleanActivity && rec.key.activity != null) { 6793 rec.key.activity.pendingResults.remove(rec.ref); 6794 } 6795 } 6796 6797 @Override getPackageForIntentSender(IIntentSender pendingResult)6798 public String getPackageForIntentSender(IIntentSender pendingResult) { 6799 if (!(pendingResult instanceof PendingIntentRecord)) { 6800 return null; 6801 } 6802 try { 6803 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6804 return res.key.packageName; 6805 } catch (ClassCastException e) { 6806 } 6807 return null; 6808 } 6809 6810 @Override getUidForIntentSender(IIntentSender sender)6811 public int getUidForIntentSender(IIntentSender sender) { 6812 if (sender instanceof PendingIntentRecord) { 6813 try { 6814 PendingIntentRecord res = (PendingIntentRecord)sender; 6815 return res.uid; 6816 } catch (ClassCastException e) { 6817 } 6818 } 6819 return -1; 6820 } 6821 6822 @Override isIntentSenderTargetedToPackage(IIntentSender pendingResult)6823 public boolean isIntentSenderTargetedToPackage(IIntentSender pendingResult) { 6824 if (!(pendingResult instanceof PendingIntentRecord)) { 6825 return false; 6826 } 6827 try { 6828 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6829 if (res.key.allIntents == null) { 6830 return false; 6831 } 6832 for (int i=0; i<res.key.allIntents.length; i++) { 6833 Intent intent = res.key.allIntents[i]; 6834 if (intent.getPackage() != null && intent.getComponent() != null) { 6835 return false; 6836 } 6837 } 6838 return true; 6839 } catch (ClassCastException e) { 6840 } 6841 return false; 6842 } 6843 6844 @Override isIntentSenderAnActivity(IIntentSender pendingResult)6845 public boolean isIntentSenderAnActivity(IIntentSender pendingResult) { 6846 if (!(pendingResult instanceof PendingIntentRecord)) { 6847 return false; 6848 } 6849 try { 6850 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6851 if (res.key.type == ActivityManager.INTENT_SENDER_ACTIVITY) { 6852 return true; 6853 } 6854 return false; 6855 } catch (ClassCastException e) { 6856 } 6857 return false; 6858 } 6859 6860 @Override getIntentForIntentSender(IIntentSender pendingResult)6861 public Intent getIntentForIntentSender(IIntentSender pendingResult) { 6862 if (!(pendingResult instanceof PendingIntentRecord)) { 6863 return null; 6864 } 6865 try { 6866 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6867 return res.key.requestIntent != null ? new Intent(res.key.requestIntent) : null; 6868 } catch (ClassCastException e) { 6869 } 6870 return null; 6871 } 6872 6873 @Override getTagForIntentSender(IIntentSender pendingResult, String prefix)6874 public String getTagForIntentSender(IIntentSender pendingResult, String prefix) { 6875 if (!(pendingResult instanceof PendingIntentRecord)) { 6876 return null; 6877 } 6878 try { 6879 PendingIntentRecord res = (PendingIntentRecord)pendingResult; 6880 synchronized (this) { 6881 return getTagForIntentSenderLocked(res, prefix); 6882 } 6883 } catch (ClassCastException e) { 6884 } 6885 return null; 6886 } 6887 getTagForIntentSenderLocked(PendingIntentRecord res, String prefix)6888 String getTagForIntentSenderLocked(PendingIntentRecord res, String prefix) { 6889 final Intent intent = res.key.requestIntent; 6890 if (intent != null) { 6891 if (res.lastTag != null && res.lastTagPrefix == prefix && (res.lastTagPrefix == null 6892 || res.lastTagPrefix.equals(prefix))) { 6893 return res.lastTag; 6894 } 6895 res.lastTagPrefix = prefix; 6896 final StringBuilder sb = new StringBuilder(128); 6897 if (prefix != null) { 6898 sb.append(prefix); 6899 } 6900 if (intent.getAction() != null) { 6901 sb.append(intent.getAction()); 6902 } else if (intent.getComponent() != null) { 6903 intent.getComponent().appendShortString(sb); 6904 } else { 6905 sb.append("?"); 6906 } 6907 return res.lastTag = sb.toString(); 6908 } 6909 return null; 6910 } 6911 6912 @Override setProcessLimit(int max)6913 public void setProcessLimit(int max) { 6914 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 6915 "setProcessLimit()"); 6916 synchronized (this) { 6917 mProcessLimit = max < 0 ? ProcessList.MAX_CACHED_APPS : max; 6918 mProcessLimitOverride = max; 6919 } 6920 trimApplications(); 6921 } 6922 6923 @Override 6924 public int getProcessLimit() { 6925 synchronized (this) { 6926 return mProcessLimitOverride; 6927 } 6928 } 6929 6930 void foregroundTokenDied(ForegroundToken token) { 6931 synchronized (ActivityManagerService.this) { 6932 synchronized (mPidsSelfLocked) { 6933 ForegroundToken cur 6934 = mForegroundProcesses.get(token.pid); 6935 if (cur != token) { 6936 return; 6937 } 6938 mForegroundProcesses.remove(token.pid); 6939 ProcessRecord pr = mPidsSelfLocked.get(token.pid); 6940 if (pr == null) { 6941 return; 6942 } 6943 pr.forcingToForeground = null; 6944 updateProcessForegroundLocked(pr, false, false); 6945 } 6946 updateOomAdjLocked(); 6947 } 6948 } 6949 6950 @Override 6951 public void setProcessForeground(IBinder token, int pid, boolean isForeground) { 6952 enforceCallingPermission(android.Manifest.permission.SET_PROCESS_LIMIT, 6953 "setProcessForeground()"); 6954 synchronized(this) { 6955 boolean changed = false; 6956 6957 synchronized (mPidsSelfLocked) { 6958 ProcessRecord pr = mPidsSelfLocked.get(pid); 6959 if (pr == null && isForeground) { 6960 Slog.w(TAG, "setProcessForeground called on unknown pid: " + pid); 6961 return; 6962 } 6963 ForegroundToken oldToken = mForegroundProcesses.get(pid); 6964 if (oldToken != null) { 6965 oldToken.token.unlinkToDeath(oldToken, 0); 6966 mForegroundProcesses.remove(pid); 6967 if (pr != null) { 6968 pr.forcingToForeground = null; 6969 } 6970 changed = true; 6971 } 6972 if (isForeground && token != null) { 6973 ForegroundToken newToken = new ForegroundToken() { 6974 @Override 6975 public void binderDied() { 6976 foregroundTokenDied(this); 6977 } 6978 }; 6979 newToken.pid = pid; 6980 newToken.token = token; 6981 try { 6982 token.linkToDeath(newToken, 0); 6983 mForegroundProcesses.put(pid, newToken); 6984 pr.forcingToForeground = token; 6985 changed = true; 6986 } catch (RemoteException e) { 6987 // If the process died while doing this, we will later 6988 // do the cleanup with the process death link. 6989 } 6990 } 6991 } 6992 6993 if (changed) { 6994 updateOomAdjLocked(); 6995 } 6996 } 6997 } 6998 6999 // ========================================================= 7000 // PROCESS INFO 7001 // ========================================================= 7002 7003 static class ProcessInfoService extends IProcessInfoService.Stub { 7004 final ActivityManagerService mActivityManagerService; 7005 ProcessInfoService(ActivityManagerService activityManagerService) { 7006 mActivityManagerService = activityManagerService; 7007 } 7008 7009 @Override 7010 public void getProcessStatesFromPids(/*in*/ int[] pids, /*out*/ int[] states) { 7011 mActivityManagerService.getProcessStatesForPIDs(/*in*/ pids, /*out*/ states); 7012 } 7013 } 7014 7015 /** 7016 * For each PID in the given input array, write the current process state 7017 * for that process into the output array, or -1 to indicate that no 7018 * process with the given PID exists. 7019 */ 7020 public void getProcessStatesForPIDs(/*in*/ int[] pids, /*out*/ int[] states) { 7021 if (pids == null) { 7022 throw new NullPointerException("pids"); 7023 } else if (states == null) { 7024 throw new NullPointerException("states"); 7025 } else if (pids.length != states.length) { 7026 throw new IllegalArgumentException("input and output arrays have different lengths!"); 7027 } 7028 7029 synchronized (mPidsSelfLocked) { 7030 for (int i = 0; i < pids.length; i++) { 7031 ProcessRecord pr = mPidsSelfLocked.get(pids[i]); 7032 states[i] = (pr == null) ? ActivityManager.PROCESS_STATE_NONEXISTENT : 7033 pr.curProcState; 7034 } 7035 } 7036 } 7037 7038 // ========================================================= 7039 // PERMISSIONS 7040 // ========================================================= 7041 7042 static class PermissionController extends IPermissionController.Stub { 7043 ActivityManagerService mActivityManagerService; 7044 PermissionController(ActivityManagerService activityManagerService) { 7045 mActivityManagerService = activityManagerService; 7046 } 7047 7048 @Override 7049 public boolean checkPermission(String permission, int pid, int uid) { 7050 return mActivityManagerService.checkPermission(permission, pid, 7051 uid) == PackageManager.PERMISSION_GRANTED; 7052 } 7053 7054 @Override 7055 public String[] getPackagesForUid(int uid) { 7056 return mActivityManagerService.mContext.getPackageManager() 7057 .getPackagesForUid(uid); 7058 } 7059 7060 @Override 7061 public boolean isRuntimePermission(String permission) { 7062 try { 7063 PermissionInfo info = mActivityManagerService.mContext.getPackageManager() 7064 .getPermissionInfo(permission, 0); 7065 return info.protectionLevel == PermissionInfo.PROTECTION_DANGEROUS; 7066 } catch (NameNotFoundException nnfe) { 7067 Slog.e(TAG, "No such permission: "+ permission, nnfe); 7068 } 7069 return false; 7070 } 7071 } 7072 7073 class IntentFirewallInterface implements IntentFirewall.AMSInterface { 7074 @Override 7075 public int checkComponentPermission(String permission, int pid, int uid, 7076 int owningUid, boolean exported) { 7077 return ActivityManagerService.this.checkComponentPermission(permission, pid, uid, 7078 owningUid, exported); 7079 } 7080 7081 @Override 7082 public Object getAMSLock() { 7083 return ActivityManagerService.this; 7084 } 7085 } 7086 7087 /** 7088 * This can be called with or without the global lock held. 7089 */ 7090 int checkComponentPermission(String permission, int pid, int uid, 7091 int owningUid, boolean exported) { 7092 if (pid == MY_PID) { 7093 return PackageManager.PERMISSION_GRANTED; 7094 } 7095 return ActivityManager.checkComponentPermission(permission, uid, 7096 owningUid, exported); 7097 } 7098 7099 /** 7100 * As the only public entry point for permissions checking, this method 7101 * can enforce the semantic that requesting a check on a null global 7102 * permission is automatically denied. (Internally a null permission 7103 * string is used when calling {@link #checkComponentPermission} in cases 7104 * when only uid-based security is needed.) 7105 * 7106 * This can be called with or without the global lock held. 7107 */ 7108 @Override 7109 public int checkPermission(String permission, int pid, int uid) { 7110 if (permission == null) { 7111 return PackageManager.PERMISSION_DENIED; 7112 } 7113 return checkComponentPermission(permission, pid, uid, -1, true); 7114 } 7115 7116 @Override 7117 public int checkPermissionWithToken(String permission, int pid, int uid, IBinder callerToken) { 7118 if (permission == null) { 7119 return PackageManager.PERMISSION_DENIED; 7120 } 7121 7122 // We might be performing an operation on behalf of an indirect binder 7123 // invocation, e.g. via {@link #openContentUri}. Check and adjust the 7124 // client identity accordingly before proceeding. 7125 Identity tlsIdentity = sCallerIdentity.get(); 7126 if (tlsIdentity != null && tlsIdentity.token == callerToken) { 7127 Slog.d(TAG, "checkComponentPermission() adjusting {pid,uid} to {" 7128 + tlsIdentity.pid + "," + tlsIdentity.uid + "}"); 7129 uid = tlsIdentity.uid; 7130 pid = tlsIdentity.pid; 7131 } 7132 7133 return checkComponentPermission(permission, pid, uid, -1, true); 7134 } 7135 7136 /** 7137 * Binder IPC calls go through the public entry point. 7138 * This can be called with or without the global lock held. 7139 */ 7140 int checkCallingPermission(String permission) { 7141 return checkPermission(permission, 7142 Binder.getCallingPid(), 7143 UserHandle.getAppId(Binder.getCallingUid())); 7144 } 7145 7146 /** 7147 * This can be called with or without the global lock held. 7148 */ 7149 void enforceCallingPermission(String permission, String func) { 7150 if (checkCallingPermission(permission) 7151 == PackageManager.PERMISSION_GRANTED) { 7152 return; 7153 } 7154 7155 String msg = "Permission Denial: " + func + " from pid=" 7156 + Binder.getCallingPid() 7157 + ", uid=" + Binder.getCallingUid() 7158 + " requires " + permission; 7159 Slog.w(TAG, msg); 7160 throw new SecurityException(msg); 7161 } 7162 7163 /** 7164 * Determine if UID is holding permissions required to access {@link Uri} in 7165 * the given {@link ProviderInfo}. Final permission checking is always done 7166 * in {@link ContentProvider}. 7167 */ 7168 private final boolean checkHoldingPermissionsLocked( 7169 IPackageManager pm, ProviderInfo pi, GrantUri grantUri, int uid, final int modeFlags) { 7170 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7171 "checkHoldingPermissionsLocked: uri=" + grantUri + " uid=" + uid); 7172 if (UserHandle.getUserId(uid) != grantUri.sourceUserId) { 7173 if (ActivityManager.checkComponentPermission(INTERACT_ACROSS_USERS, uid, -1, true) 7174 != PERMISSION_GRANTED) { 7175 return false; 7176 } 7177 } 7178 return checkHoldingPermissionsInternalLocked(pm, pi, grantUri, uid, modeFlags, true); 7179 } 7180 7181 private final boolean checkHoldingPermissionsInternalLocked(IPackageManager pm, ProviderInfo pi, 7182 GrantUri grantUri, int uid, final int modeFlags, boolean considerUidPermissions) { 7183 if (pi.applicationInfo.uid == uid) { 7184 return true; 7185 } else if (!pi.exported) { 7186 return false; 7187 } 7188 7189 boolean readMet = (modeFlags & Intent.FLAG_GRANT_READ_URI_PERMISSION) == 0; 7190 boolean writeMet = (modeFlags & Intent.FLAG_GRANT_WRITE_URI_PERMISSION) == 0; 7191 try { 7192 // check if target holds top-level <provider> permissions 7193 if (!readMet && pi.readPermission != null && considerUidPermissions 7194 && (pm.checkUidPermission(pi.readPermission, uid) == PERMISSION_GRANTED)) { 7195 readMet = true; 7196 } 7197 if (!writeMet && pi.writePermission != null && considerUidPermissions 7198 && (pm.checkUidPermission(pi.writePermission, uid) == PERMISSION_GRANTED)) { 7199 writeMet = true; 7200 } 7201 7202 // track if unprotected read/write is allowed; any denied 7203 // <path-permission> below removes this ability 7204 boolean allowDefaultRead = pi.readPermission == null; 7205 boolean allowDefaultWrite = pi.writePermission == null; 7206 7207 // check if target holds any <path-permission> that match uri 7208 final PathPermission[] pps = pi.pathPermissions; 7209 if (pps != null) { 7210 final String path = grantUri.uri.getPath(); 7211 int i = pps.length; 7212 while (i > 0 && (!readMet || !writeMet)) { 7213 i--; 7214 PathPermission pp = pps[i]; 7215 if (pp.match(path)) { 7216 if (!readMet) { 7217 final String pprperm = pp.getReadPermission(); 7218 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7219 "Checking read perm for " + pprperm + " for " + pp.getPath() 7220 + ": match=" + pp.match(path) 7221 + " check=" + pm.checkUidPermission(pprperm, uid)); 7222 if (pprperm != null) { 7223 if (considerUidPermissions && pm.checkUidPermission(pprperm, uid) 7224 == PERMISSION_GRANTED) { 7225 readMet = true; 7226 } else { 7227 allowDefaultRead = false; 7228 } 7229 } 7230 } 7231 if (!writeMet) { 7232 final String ppwperm = pp.getWritePermission(); 7233 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7234 "Checking write perm " + ppwperm + " for " + pp.getPath() 7235 + ": match=" + pp.match(path) 7236 + " check=" + pm.checkUidPermission(ppwperm, uid)); 7237 if (ppwperm != null) { 7238 if (considerUidPermissions && pm.checkUidPermission(ppwperm, uid) 7239 == PERMISSION_GRANTED) { 7240 writeMet = true; 7241 } else { 7242 allowDefaultWrite = false; 7243 } 7244 } 7245 } 7246 } 7247 } 7248 } 7249 7250 // grant unprotected <provider> read/write, if not blocked by 7251 // <path-permission> above 7252 if (allowDefaultRead) readMet = true; 7253 if (allowDefaultWrite) writeMet = true; 7254 7255 } catch (RemoteException e) { 7256 return false; 7257 } 7258 7259 return readMet && writeMet; 7260 } 7261 7262 private ProviderInfo getProviderInfoLocked(String authority, int userHandle) { 7263 ProviderInfo pi = null; 7264 ContentProviderRecord cpr = mProviderMap.getProviderByName(authority, userHandle); 7265 if (cpr != null) { 7266 pi = cpr.info; 7267 } else { 7268 try { 7269 pi = AppGlobals.getPackageManager().resolveContentProvider( 7270 authority, PackageManager.GET_URI_PERMISSION_PATTERNS, userHandle); 7271 } catch (RemoteException ex) { 7272 } 7273 } 7274 return pi; 7275 } 7276 7277 private UriPermission findUriPermissionLocked(int targetUid, GrantUri grantUri) { 7278 final ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid); 7279 if (targetUris != null) { 7280 return targetUris.get(grantUri); 7281 } 7282 return null; 7283 } 7284 7285 private UriPermission findOrCreateUriPermissionLocked(String sourcePkg, 7286 String targetPkg, int targetUid, GrantUri grantUri) { 7287 ArrayMap<GrantUri, UriPermission> targetUris = mGrantedUriPermissions.get(targetUid); 7288 if (targetUris == null) { 7289 targetUris = Maps.newArrayMap(); 7290 mGrantedUriPermissions.put(targetUid, targetUris); 7291 } 7292 7293 UriPermission perm = targetUris.get(grantUri); 7294 if (perm == null) { 7295 perm = new UriPermission(sourcePkg, targetPkg, targetUid, grantUri); 7296 targetUris.put(grantUri, perm); 7297 } 7298 7299 return perm; 7300 } 7301 7302 private final boolean checkUriPermissionLocked(GrantUri grantUri, int uid, 7303 final int modeFlags) { 7304 final boolean persistable = (modeFlags & Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) != 0; 7305 final int minStrength = persistable ? UriPermission.STRENGTH_PERSISTABLE 7306 : UriPermission.STRENGTH_OWNED; 7307 7308 // Root gets to do everything. 7309 if (uid == 0) { 7310 return true; 7311 } 7312 7313 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid); 7314 if (perms == null) return false; 7315 7316 // First look for exact match 7317 final UriPermission exactPerm = perms.get(grantUri); 7318 if (exactPerm != null && exactPerm.getStrength(modeFlags) >= minStrength) { 7319 return true; 7320 } 7321 7322 // No exact match, look for prefixes 7323 final int N = perms.size(); 7324 for (int i = 0; i < N; i++) { 7325 final UriPermission perm = perms.valueAt(i); 7326 if (perm.uri.prefix && grantUri.uri.isPathPrefixMatch(perm.uri.uri) 7327 && perm.getStrength(modeFlags) >= minStrength) { 7328 return true; 7329 } 7330 } 7331 7332 return false; 7333 } 7334 7335 /** 7336 * @param uri This uri must NOT contain an embedded userId. 7337 * @param userId The userId in which the uri is to be resolved. 7338 */ 7339 @Override checkUriPermission(Uri uri, int pid, int uid, final int modeFlags, int userId, IBinder callerToken)7340 public int checkUriPermission(Uri uri, int pid, int uid, 7341 final int modeFlags, int userId, IBinder callerToken) { 7342 enforceNotIsolatedCaller("checkUriPermission"); 7343 7344 // Another redirected-binder-call permissions check as in 7345 // {@link checkPermissionWithToken}. 7346 Identity tlsIdentity = sCallerIdentity.get(); 7347 if (tlsIdentity != null && tlsIdentity.token == callerToken) { 7348 uid = tlsIdentity.uid; 7349 pid = tlsIdentity.pid; 7350 } 7351 7352 // Our own process gets to do everything. 7353 if (pid == MY_PID) { 7354 return PackageManager.PERMISSION_GRANTED; 7355 } 7356 synchronized (this) { 7357 return checkUriPermissionLocked(new GrantUri(userId, uri, false), uid, modeFlags) 7358 ? PackageManager.PERMISSION_GRANTED 7359 : PackageManager.PERMISSION_DENIED; 7360 } 7361 } 7362 7363 /** 7364 * Check if the targetPkg can be granted permission to access uri by 7365 * the callingUid using the given modeFlags. Throws a security exception 7366 * if callingUid is not allowed to do this. Returns the uid of the target 7367 * if the URI permission grant should be performed; returns -1 if it is not 7368 * needed (for example targetPkg already has permission to access the URI). 7369 * If you already know the uid of the target, you can supply it in 7370 * lastTargetUid else set that to -1. 7371 */ checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, final int modeFlags, int lastTargetUid)7372 int checkGrantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, 7373 final int modeFlags, int lastTargetUid) { 7374 if (!Intent.isAccessUriMode(modeFlags)) { 7375 return -1; 7376 } 7377 7378 if (targetPkg != null) { 7379 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7380 "Checking grant " + targetPkg + " permission to " + grantUri); 7381 } 7382 7383 final IPackageManager pm = AppGlobals.getPackageManager(); 7384 7385 // If this is not a content: uri, we can't do anything with it. 7386 if (!ContentResolver.SCHEME_CONTENT.equals(grantUri.uri.getScheme())) { 7387 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7388 "Can't grant URI permission for non-content URI: " + grantUri); 7389 return -1; 7390 } 7391 7392 final String authority = grantUri.uri.getAuthority(); 7393 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 7394 if (pi == null) { 7395 Slog.w(TAG, "No content provider found for permission check: " + 7396 grantUri.uri.toSafeString()); 7397 return -1; 7398 } 7399 7400 int targetUid = lastTargetUid; 7401 if (targetUid < 0 && targetPkg != null) { 7402 try { 7403 targetUid = pm.getPackageUid(targetPkg, UserHandle.getUserId(callingUid)); 7404 if (targetUid < 0) { 7405 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7406 "Can't grant URI permission no uid for: " + targetPkg); 7407 return -1; 7408 } 7409 } catch (RemoteException ex) { 7410 return -1; 7411 } 7412 } 7413 7414 if (targetUid >= 0) { 7415 // First... does the target actually need this permission? 7416 if (checkHoldingPermissionsLocked(pm, pi, grantUri, targetUid, modeFlags)) { 7417 // No need to grant the target this permission. 7418 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7419 "Target " + targetPkg + " already has full permission to " + grantUri); 7420 return -1; 7421 } 7422 } else { 7423 // First... there is no target package, so can anyone access it? 7424 boolean allowed = pi.exported; 7425 if ((modeFlags&Intent.FLAG_GRANT_READ_URI_PERMISSION) != 0) { 7426 if (pi.readPermission != null) { 7427 allowed = false; 7428 } 7429 } 7430 if ((modeFlags&Intent.FLAG_GRANT_WRITE_URI_PERMISSION) != 0) { 7431 if (pi.writePermission != null) { 7432 allowed = false; 7433 } 7434 } 7435 if (allowed) { 7436 return -1; 7437 } 7438 } 7439 7440 /* There is a special cross user grant if: 7441 * - The target is on another user. 7442 * - Apps on the current user can access the uri without any uid permissions. 7443 * In this case, we grant a uri permission, even if the ContentProvider does not normally 7444 * grant uri permissions. 7445 */ 7446 boolean specialCrossUserGrant = UserHandle.getUserId(targetUid) != grantUri.sourceUserId 7447 && checkHoldingPermissionsInternalLocked(pm, pi, grantUri, callingUid, 7448 modeFlags, false /*without considering the uid permissions*/); 7449 7450 // Second... is the provider allowing granting of URI permissions? 7451 if (!specialCrossUserGrant) { 7452 if (!pi.grantUriPermissions) { 7453 throw new SecurityException("Provider " + pi.packageName 7454 + "/" + pi.name 7455 + " does not allow granting of Uri permissions (uri " 7456 + grantUri + ")"); 7457 } 7458 if (pi.uriPermissionPatterns != null) { 7459 final int N = pi.uriPermissionPatterns.length; 7460 boolean allowed = false; 7461 for (int i=0; i<N; i++) { 7462 if (pi.uriPermissionPatterns[i] != null 7463 && pi.uriPermissionPatterns[i].match(grantUri.uri.getPath())) { 7464 allowed = true; 7465 break; 7466 } 7467 } 7468 if (!allowed) { 7469 throw new SecurityException("Provider " + pi.packageName 7470 + "/" + pi.name 7471 + " does not allow granting of permission to path of Uri " 7472 + grantUri); 7473 } 7474 } 7475 } 7476 7477 // Third... does the caller itself have permission to access 7478 // this uri? 7479 if (UserHandle.getAppId(callingUid) != Process.SYSTEM_UID) { 7480 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) { 7481 // Require they hold a strong enough Uri permission 7482 if (!checkUriPermissionLocked(grantUri, callingUid, modeFlags)) { 7483 throw new SecurityException("Uid " + callingUid 7484 + " does not have permission to uri " + grantUri); 7485 } 7486 } 7487 } 7488 return targetUid; 7489 } 7490 7491 /** 7492 * @param uri This uri must NOT contain an embedded userId. 7493 * @param userId The userId in which the uri is to be resolved. 7494 */ 7495 @Override checkGrantUriPermission(int callingUid, String targetPkg, Uri uri, final int modeFlags, int userId)7496 public int checkGrantUriPermission(int callingUid, String targetPkg, Uri uri, 7497 final int modeFlags, int userId) { 7498 enforceNotIsolatedCaller("checkGrantUriPermission"); 7499 synchronized(this) { 7500 return checkGrantUriPermissionLocked(callingUid, targetPkg, 7501 new GrantUri(userId, uri, false), modeFlags, -1); 7502 } 7503 } 7504 grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri, final int modeFlags, UriPermissionOwner owner)7505 void grantUriPermissionUncheckedLocked(int targetUid, String targetPkg, GrantUri grantUri, 7506 final int modeFlags, UriPermissionOwner owner) { 7507 if (!Intent.isAccessUriMode(modeFlags)) { 7508 return; 7509 } 7510 7511 // So here we are: the caller has the assumed permission 7512 // to the uri, and the target doesn't. Let's now give this to 7513 // the target. 7514 7515 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7516 "Granting " + targetPkg + "/" + targetUid + " permission to " + grantUri); 7517 7518 final String authority = grantUri.uri.getAuthority(); 7519 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 7520 if (pi == null) { 7521 Slog.w(TAG, "No content provider found for grant: " + grantUri.toSafeString()); 7522 return; 7523 } 7524 7525 if ((modeFlags & Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) != 0) { 7526 grantUri.prefix = true; 7527 } 7528 final UriPermission perm = findOrCreateUriPermissionLocked( 7529 pi.packageName, targetPkg, targetUid, grantUri); 7530 perm.grantModes(modeFlags, owner); 7531 } 7532 grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, final int modeFlags, UriPermissionOwner owner, int targetUserId)7533 void grantUriPermissionLocked(int callingUid, String targetPkg, GrantUri grantUri, 7534 final int modeFlags, UriPermissionOwner owner, int targetUserId) { 7535 if (targetPkg == null) { 7536 throw new NullPointerException("targetPkg"); 7537 } 7538 int targetUid; 7539 final IPackageManager pm = AppGlobals.getPackageManager(); 7540 try { 7541 targetUid = pm.getPackageUid(targetPkg, targetUserId); 7542 } catch (RemoteException ex) { 7543 return; 7544 } 7545 7546 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, modeFlags, 7547 targetUid); 7548 if (targetUid < 0) { 7549 return; 7550 } 7551 7552 grantUriPermissionUncheckedLocked(targetUid, targetPkg, grantUri, modeFlags, 7553 owner); 7554 } 7555 7556 static class NeededUriGrants extends ArrayList<GrantUri> { 7557 final String targetPkg; 7558 final int targetUid; 7559 final int flags; 7560 NeededUriGrants(String targetPkg, int targetUid, int flags)7561 NeededUriGrants(String targetPkg, int targetUid, int flags) { 7562 this.targetPkg = targetPkg; 7563 this.targetUid = targetUid; 7564 this.flags = flags; 7565 } 7566 } 7567 7568 /** 7569 * Like checkGrantUriPermissionLocked, but takes an Intent. 7570 */ checkGrantUriPermissionFromIntentLocked(int callingUid, String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId)7571 NeededUriGrants checkGrantUriPermissionFromIntentLocked(int callingUid, 7572 String targetPkg, Intent intent, int mode, NeededUriGrants needed, int targetUserId) { 7573 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7574 "Checking URI perm to data=" + (intent != null ? intent.getData() : null) 7575 + " clip=" + (intent != null ? intent.getClipData() : null) 7576 + " from " + intent + "; flags=0x" 7577 + Integer.toHexString(intent != null ? intent.getFlags() : 0)); 7578 7579 if (targetPkg == null) { 7580 throw new NullPointerException("targetPkg"); 7581 } 7582 7583 if (intent == null) { 7584 return null; 7585 } 7586 Uri data = intent.getData(); 7587 ClipData clip = intent.getClipData(); 7588 if (data == null && clip == null) { 7589 return null; 7590 } 7591 // Default userId for uris in the intent (if they don't specify it themselves) 7592 int contentUserHint = intent.getContentUserHint(); 7593 if (contentUserHint == UserHandle.USER_CURRENT) { 7594 contentUserHint = UserHandle.getUserId(callingUid); 7595 } 7596 final IPackageManager pm = AppGlobals.getPackageManager(); 7597 int targetUid; 7598 if (needed != null) { 7599 targetUid = needed.targetUid; 7600 } else { 7601 try { 7602 targetUid = pm.getPackageUid(targetPkg, targetUserId); 7603 } catch (RemoteException ex) { 7604 return null; 7605 } 7606 if (targetUid < 0) { 7607 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7608 "Can't grant URI permission no uid for: " + targetPkg 7609 + " on user " + targetUserId); 7610 return null; 7611 } 7612 } 7613 if (data != null) { 7614 GrantUri grantUri = GrantUri.resolve(contentUserHint, data); 7615 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode, 7616 targetUid); 7617 if (targetUid > 0) { 7618 if (needed == null) { 7619 needed = new NeededUriGrants(targetPkg, targetUid, mode); 7620 } 7621 needed.add(grantUri); 7622 } 7623 } 7624 if (clip != null) { 7625 for (int i=0; i<clip.getItemCount(); i++) { 7626 Uri uri = clip.getItemAt(i).getUri(); 7627 if (uri != null) { 7628 GrantUri grantUri = GrantUri.resolve(contentUserHint, uri); 7629 targetUid = checkGrantUriPermissionLocked(callingUid, targetPkg, grantUri, mode, 7630 targetUid); 7631 if (targetUid > 0) { 7632 if (needed == null) { 7633 needed = new NeededUriGrants(targetPkg, targetUid, mode); 7634 } 7635 needed.add(grantUri); 7636 } 7637 } else { 7638 Intent clipIntent = clip.getItemAt(i).getIntent(); 7639 if (clipIntent != null) { 7640 NeededUriGrants newNeeded = checkGrantUriPermissionFromIntentLocked( 7641 callingUid, targetPkg, clipIntent, mode, needed, targetUserId); 7642 if (newNeeded != null) { 7643 needed = newNeeded; 7644 } 7645 } 7646 } 7647 } 7648 } 7649 7650 return needed; 7651 } 7652 7653 /** 7654 * Like grantUriPermissionUncheckedLocked, but takes an Intent. 7655 */ grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed, UriPermissionOwner owner)7656 void grantUriPermissionUncheckedFromIntentLocked(NeededUriGrants needed, 7657 UriPermissionOwner owner) { 7658 if (needed != null) { 7659 for (int i=0; i<needed.size(); i++) { 7660 GrantUri grantUri = needed.get(i); 7661 grantUriPermissionUncheckedLocked(needed.targetUid, needed.targetPkg, 7662 grantUri, needed.flags, owner); 7663 } 7664 } 7665 } 7666 grantUriPermissionFromIntentLocked(int callingUid, String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId)7667 void grantUriPermissionFromIntentLocked(int callingUid, 7668 String targetPkg, Intent intent, UriPermissionOwner owner, int targetUserId) { 7669 NeededUriGrants needed = checkGrantUriPermissionFromIntentLocked(callingUid, targetPkg, 7670 intent, intent != null ? intent.getFlags() : 0, null, targetUserId); 7671 if (needed == null) { 7672 return; 7673 } 7674 7675 grantUriPermissionUncheckedFromIntentLocked(needed, owner); 7676 } 7677 7678 /** 7679 * @param uri This uri must NOT contain an embedded userId. 7680 * @param userId The userId in which the uri is to be resolved. 7681 */ 7682 @Override grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, final int modeFlags, int userId)7683 public void grantUriPermission(IApplicationThread caller, String targetPkg, Uri uri, 7684 final int modeFlags, int userId) { 7685 enforceNotIsolatedCaller("grantUriPermission"); 7686 GrantUri grantUri = new GrantUri(userId, uri, false); 7687 synchronized(this) { 7688 final ProcessRecord r = getRecordForAppLocked(caller); 7689 if (r == null) { 7690 throw new SecurityException("Unable to find app for caller " 7691 + caller 7692 + " when granting permission to uri " + grantUri); 7693 } 7694 if (targetPkg == null) { 7695 throw new IllegalArgumentException("null target"); 7696 } 7697 if (grantUri == null) { 7698 throw new IllegalArgumentException("null uri"); 7699 } 7700 7701 Preconditions.checkFlagsArgument(modeFlags, Intent.FLAG_GRANT_READ_URI_PERMISSION 7702 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION 7703 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION 7704 | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION); 7705 7706 grantUriPermissionLocked(r.uid, targetPkg, grantUri, modeFlags, null, 7707 UserHandle.getUserId(r.uid)); 7708 } 7709 } 7710 removeUriPermissionIfNeededLocked(UriPermission perm)7711 void removeUriPermissionIfNeededLocked(UriPermission perm) { 7712 if (perm.modeFlags == 0) { 7713 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get( 7714 perm.targetUid); 7715 if (perms != null) { 7716 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7717 "Removing " + perm.targetUid + " permission to " + perm.uri); 7718 7719 perms.remove(perm.uri); 7720 if (perms.isEmpty()) { 7721 mGrantedUriPermissions.remove(perm.targetUid); 7722 } 7723 } 7724 } 7725 } 7726 revokeUriPermissionLocked(int callingUid, GrantUri grantUri, final int modeFlags)7727 private void revokeUriPermissionLocked(int callingUid, GrantUri grantUri, final int modeFlags) { 7728 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7729 "Revoking all granted permissions to " + grantUri); 7730 7731 final IPackageManager pm = AppGlobals.getPackageManager(); 7732 final String authority = grantUri.uri.getAuthority(); 7733 final ProviderInfo pi = getProviderInfoLocked(authority, grantUri.sourceUserId); 7734 if (pi == null) { 7735 Slog.w(TAG, "No content provider found for permission revoke: " 7736 + grantUri.toSafeString()); 7737 return; 7738 } 7739 7740 // Does the caller have this permission on the URI? 7741 if (!checkHoldingPermissionsLocked(pm, pi, grantUri, callingUid, modeFlags)) { 7742 // If they don't have direct access to the URI, then revoke any 7743 // ownerless URI permissions that have been granted to them. 7744 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 7745 if (perms != null) { 7746 boolean persistChanged = false; 7747 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 7748 final UriPermission perm = it.next(); 7749 if (perm.uri.sourceUserId == grantUri.sourceUserId 7750 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) { 7751 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7752 "Revoking non-owned " + perm.targetUid 7753 + " permission to " + perm.uri); 7754 persistChanged |= perm.revokeModes( 7755 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, false); 7756 if (perm.modeFlags == 0) { 7757 it.remove(); 7758 } 7759 } 7760 } 7761 if (perms.isEmpty()) { 7762 mGrantedUriPermissions.remove(callingUid); 7763 } 7764 if (persistChanged) { 7765 schedulePersistUriGrants(); 7766 } 7767 } 7768 return; 7769 } 7770 7771 boolean persistChanged = false; 7772 7773 // Go through all of the permissions and remove any that match. 7774 int N = mGrantedUriPermissions.size(); 7775 for (int i = 0; i < N; i++) { 7776 final int targetUid = mGrantedUriPermissions.keyAt(i); 7777 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 7778 7779 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 7780 final UriPermission perm = it.next(); 7781 if (perm.uri.sourceUserId == grantUri.sourceUserId 7782 && perm.uri.uri.isPathPrefixMatch(grantUri.uri)) { 7783 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 7784 "Revoking " + perm.targetUid + " permission to " + perm.uri); 7785 persistChanged |= perm.revokeModes( 7786 modeFlags | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, true); 7787 if (perm.modeFlags == 0) { 7788 it.remove(); 7789 } 7790 } 7791 } 7792 7793 if (perms.isEmpty()) { 7794 mGrantedUriPermissions.remove(targetUid); 7795 N--; 7796 i--; 7797 } 7798 } 7799 7800 if (persistChanged) { 7801 schedulePersistUriGrants(); 7802 } 7803 } 7804 7805 /** 7806 * @param uri This uri must NOT contain an embedded userId. 7807 * @param userId The userId in which the uri is to be resolved. 7808 */ 7809 @Override revokeUriPermission(IApplicationThread caller, Uri uri, final int modeFlags, int userId)7810 public void revokeUriPermission(IApplicationThread caller, Uri uri, final int modeFlags, 7811 int userId) { 7812 enforceNotIsolatedCaller("revokeUriPermission"); 7813 synchronized(this) { 7814 final ProcessRecord r = getRecordForAppLocked(caller); 7815 if (r == null) { 7816 throw new SecurityException("Unable to find app for caller " 7817 + caller 7818 + " when revoking permission to uri " + uri); 7819 } 7820 if (uri == null) { 7821 Slog.w(TAG, "revokeUriPermission: null uri"); 7822 return; 7823 } 7824 7825 if (!Intent.isAccessUriMode(modeFlags)) { 7826 return; 7827 } 7828 7829 final String authority = uri.getAuthority(); 7830 final ProviderInfo pi = getProviderInfoLocked(authority, userId); 7831 if (pi == null) { 7832 Slog.w(TAG, "No content provider found for permission revoke: " 7833 + uri.toSafeString()); 7834 return; 7835 } 7836 7837 revokeUriPermissionLocked(r.uid, new GrantUri(userId, uri, false), modeFlags); 7838 } 7839 } 7840 7841 /** 7842 * Remove any {@link UriPermission} granted <em>from</em> or <em>to</em> the 7843 * given package. 7844 * 7845 * @param packageName Package name to match, or {@code null} to apply to all 7846 * packages. 7847 * @param userHandle User to match, or {@link UserHandle#USER_ALL} to apply 7848 * to all users. 7849 * @param persistable If persistable grants should be removed. 7850 */ removeUriPermissionsForPackageLocked( String packageName, int userHandle, boolean persistable)7851 private void removeUriPermissionsForPackageLocked( 7852 String packageName, int userHandle, boolean persistable) { 7853 if (userHandle == UserHandle.USER_ALL && packageName == null) { 7854 throw new IllegalArgumentException("Must narrow by either package or user"); 7855 } 7856 7857 boolean persistChanged = false; 7858 7859 int N = mGrantedUriPermissions.size(); 7860 for (int i = 0; i < N; i++) { 7861 final int targetUid = mGrantedUriPermissions.keyAt(i); 7862 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 7863 7864 // Only inspect grants matching user 7865 if (userHandle == UserHandle.USER_ALL 7866 || userHandle == UserHandle.getUserId(targetUid)) { 7867 for (Iterator<UriPermission> it = perms.values().iterator(); it.hasNext();) { 7868 final UriPermission perm = it.next(); 7869 7870 // Only inspect grants matching package 7871 if (packageName == null || perm.sourcePkg.equals(packageName) 7872 || perm.targetPkg.equals(packageName)) { 7873 persistChanged |= perm.revokeModes(persistable 7874 ? ~0 : ~Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION, true); 7875 7876 // Only remove when no modes remain; any persisted grants 7877 // will keep this alive. 7878 if (perm.modeFlags == 0) { 7879 it.remove(); 7880 } 7881 } 7882 } 7883 7884 if (perms.isEmpty()) { 7885 mGrantedUriPermissions.remove(targetUid); 7886 N--; 7887 i--; 7888 } 7889 } 7890 } 7891 7892 if (persistChanged) { 7893 schedulePersistUriGrants(); 7894 } 7895 } 7896 7897 @Override newUriPermissionOwner(String name)7898 public IBinder newUriPermissionOwner(String name) { 7899 enforceNotIsolatedCaller("newUriPermissionOwner"); 7900 synchronized(this) { 7901 UriPermissionOwner owner = new UriPermissionOwner(this, name); 7902 return owner.getExternalTokenLocked(); 7903 } 7904 } 7905 7906 /** 7907 * @param uri This uri must NOT contain an embedded userId. 7908 * @param sourceUserId The userId in which the uri is to be resolved. 7909 * @param targetUserId The userId of the app that receives the grant. 7910 */ 7911 @Override grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri, final int modeFlags, int sourceUserId, int targetUserId)7912 public void grantUriPermissionFromOwner(IBinder token, int fromUid, String targetPkg, Uri uri, 7913 final int modeFlags, int sourceUserId, int targetUserId) { 7914 targetUserId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 7915 targetUserId, false, ALLOW_FULL_ONLY, "grantUriPermissionFromOwner", null); 7916 synchronized(this) { 7917 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 7918 if (owner == null) { 7919 throw new IllegalArgumentException("Unknown owner: " + token); 7920 } 7921 if (fromUid != Binder.getCallingUid()) { 7922 if (Binder.getCallingUid() != Process.myUid()) { 7923 // Only system code can grant URI permissions on behalf 7924 // of other users. 7925 throw new SecurityException("nice try"); 7926 } 7927 } 7928 if (targetPkg == null) { 7929 throw new IllegalArgumentException("null target"); 7930 } 7931 if (uri == null) { 7932 throw new IllegalArgumentException("null uri"); 7933 } 7934 7935 grantUriPermissionLocked(fromUid, targetPkg, new GrantUri(sourceUserId, uri, false), 7936 modeFlags, owner, targetUserId); 7937 } 7938 } 7939 7940 /** 7941 * @param uri This uri must NOT contain an embedded userId. 7942 * @param userId The userId in which the uri is to be resolved. 7943 */ 7944 @Override revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId)7945 public void revokeUriPermissionFromOwner(IBinder token, Uri uri, int mode, int userId) { 7946 synchronized(this) { 7947 UriPermissionOwner owner = UriPermissionOwner.fromExternalToken(token); 7948 if (owner == null) { 7949 throw new IllegalArgumentException("Unknown owner: " + token); 7950 } 7951 7952 if (uri == null) { 7953 owner.removeUriPermissionsLocked(mode); 7954 } else { 7955 owner.removeUriPermissionLocked(new GrantUri(userId, uri, false), mode); 7956 } 7957 } 7958 } 7959 schedulePersistUriGrants()7960 private void schedulePersistUriGrants() { 7961 if (!mHandler.hasMessages(PERSIST_URI_GRANTS_MSG)) { 7962 mHandler.sendMessageDelayed(mHandler.obtainMessage(PERSIST_URI_GRANTS_MSG), 7963 10 * DateUtils.SECOND_IN_MILLIS); 7964 } 7965 } 7966 writeGrantedUriPermissions()7967 private void writeGrantedUriPermissions() { 7968 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, "writeGrantedUriPermissions()"); 7969 7970 // Snapshot permissions so we can persist without lock 7971 ArrayList<UriPermission.Snapshot> persist = Lists.newArrayList(); 7972 synchronized (this) { 7973 final int size = mGrantedUriPermissions.size(); 7974 for (int i = 0; i < size; i++) { 7975 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 7976 for (UriPermission perm : perms.values()) { 7977 if (perm.persistedModeFlags != 0) { 7978 persist.add(perm.snapshot()); 7979 } 7980 } 7981 } 7982 } 7983 7984 FileOutputStream fos = null; 7985 try { 7986 fos = mGrantFile.startWrite(); 7987 7988 XmlSerializer out = new FastXmlSerializer(); 7989 out.setOutput(fos, StandardCharsets.UTF_8.name()); 7990 out.startDocument(null, true); 7991 out.startTag(null, TAG_URI_GRANTS); 7992 for (UriPermission.Snapshot perm : persist) { 7993 out.startTag(null, TAG_URI_GRANT); 7994 writeIntAttribute(out, ATTR_SOURCE_USER_ID, perm.uri.sourceUserId); 7995 writeIntAttribute(out, ATTR_TARGET_USER_ID, perm.targetUserId); 7996 out.attribute(null, ATTR_SOURCE_PKG, perm.sourcePkg); 7997 out.attribute(null, ATTR_TARGET_PKG, perm.targetPkg); 7998 out.attribute(null, ATTR_URI, String.valueOf(perm.uri.uri)); 7999 writeBooleanAttribute(out, ATTR_PREFIX, perm.uri.prefix); 8000 writeIntAttribute(out, ATTR_MODE_FLAGS, perm.persistedModeFlags); 8001 writeLongAttribute(out, ATTR_CREATED_TIME, perm.persistedCreateTime); 8002 out.endTag(null, TAG_URI_GRANT); 8003 } 8004 out.endTag(null, TAG_URI_GRANTS); 8005 out.endDocument(); 8006 8007 mGrantFile.finishWrite(fos); 8008 } catch (IOException e) { 8009 if (fos != null) { 8010 mGrantFile.failWrite(fos); 8011 } 8012 } 8013 } 8014 readGrantedUriPermissionsLocked()8015 private void readGrantedUriPermissionsLocked() { 8016 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, "readGrantedUriPermissions()"); 8017 8018 final long now = System.currentTimeMillis(); 8019 8020 FileInputStream fis = null; 8021 try { 8022 fis = mGrantFile.openRead(); 8023 final XmlPullParser in = Xml.newPullParser(); 8024 in.setInput(fis, StandardCharsets.UTF_8.name()); 8025 8026 int type; 8027 while ((type = in.next()) != END_DOCUMENT) { 8028 final String tag = in.getName(); 8029 if (type == START_TAG) { 8030 if (TAG_URI_GRANT.equals(tag)) { 8031 final int sourceUserId; 8032 final int targetUserId; 8033 final int userHandle = readIntAttribute(in, 8034 ATTR_USER_HANDLE, UserHandle.USER_NULL); 8035 if (userHandle != UserHandle.USER_NULL) { 8036 // For backwards compatibility. 8037 sourceUserId = userHandle; 8038 targetUserId = userHandle; 8039 } else { 8040 sourceUserId = readIntAttribute(in, ATTR_SOURCE_USER_ID); 8041 targetUserId = readIntAttribute(in, ATTR_TARGET_USER_ID); 8042 } 8043 final String sourcePkg = in.getAttributeValue(null, ATTR_SOURCE_PKG); 8044 final String targetPkg = in.getAttributeValue(null, ATTR_TARGET_PKG); 8045 final Uri uri = Uri.parse(in.getAttributeValue(null, ATTR_URI)); 8046 final boolean prefix = readBooleanAttribute(in, ATTR_PREFIX); 8047 final int modeFlags = readIntAttribute(in, ATTR_MODE_FLAGS); 8048 final long createdTime = readLongAttribute(in, ATTR_CREATED_TIME, now); 8049 8050 // Sanity check that provider still belongs to source package 8051 final ProviderInfo pi = getProviderInfoLocked( 8052 uri.getAuthority(), sourceUserId); 8053 if (pi != null && sourcePkg.equals(pi.packageName)) { 8054 int targetUid = -1; 8055 try { 8056 targetUid = AppGlobals.getPackageManager() 8057 .getPackageUid(targetPkg, targetUserId); 8058 } catch (RemoteException e) { 8059 } 8060 if (targetUid != -1) { 8061 final UriPermission perm = findOrCreateUriPermissionLocked( 8062 sourcePkg, targetPkg, targetUid, 8063 new GrantUri(sourceUserId, uri, prefix)); 8064 perm.initPersistedModes(modeFlags, createdTime); 8065 } 8066 } else { 8067 Slog.w(TAG, "Persisted grant for " + uri + " had source " + sourcePkg 8068 + " but instead found " + pi); 8069 } 8070 } 8071 } 8072 } 8073 } catch (FileNotFoundException e) { 8074 // Missing grants is okay 8075 } catch (IOException e) { 8076 Slog.wtf(TAG, "Failed reading Uri grants", e); 8077 } catch (XmlPullParserException e) { 8078 Slog.wtf(TAG, "Failed reading Uri grants", e); 8079 } finally { 8080 IoUtils.closeQuietly(fis); 8081 } 8082 } 8083 8084 /** 8085 * @param uri This uri must NOT contain an embedded userId. 8086 * @param userId The userId in which the uri is to be resolved. 8087 */ 8088 @Override takePersistableUriPermission(Uri uri, final int modeFlags, int userId)8089 public void takePersistableUriPermission(Uri uri, final int modeFlags, int userId) { 8090 enforceNotIsolatedCaller("takePersistableUriPermission"); 8091 8092 Preconditions.checkFlagsArgument(modeFlags, 8093 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 8094 8095 synchronized (this) { 8096 final int callingUid = Binder.getCallingUid(); 8097 boolean persistChanged = false; 8098 GrantUri grantUri = new GrantUri(userId, uri, false); 8099 8100 UriPermission exactPerm = findUriPermissionLocked(callingUid, 8101 new GrantUri(userId, uri, false)); 8102 UriPermission prefixPerm = findUriPermissionLocked(callingUid, 8103 new GrantUri(userId, uri, true)); 8104 8105 final boolean exactValid = (exactPerm != null) 8106 && ((modeFlags & exactPerm.persistableModeFlags) == modeFlags); 8107 final boolean prefixValid = (prefixPerm != null) 8108 && ((modeFlags & prefixPerm.persistableModeFlags) == modeFlags); 8109 8110 if (!(exactValid || prefixValid)) { 8111 throw new SecurityException("No persistable permission grants found for UID " 8112 + callingUid + " and Uri " + grantUri.toSafeString()); 8113 } 8114 8115 if (exactValid) { 8116 persistChanged |= exactPerm.takePersistableModes(modeFlags); 8117 } 8118 if (prefixValid) { 8119 persistChanged |= prefixPerm.takePersistableModes(modeFlags); 8120 } 8121 8122 persistChanged |= maybePrunePersistedUriGrantsLocked(callingUid); 8123 8124 if (persistChanged) { 8125 schedulePersistUriGrants(); 8126 } 8127 } 8128 } 8129 8130 /** 8131 * @param uri This uri must NOT contain an embedded userId. 8132 * @param userId The userId in which the uri is to be resolved. 8133 */ 8134 @Override releasePersistableUriPermission(Uri uri, final int modeFlags, int userId)8135 public void releasePersistableUriPermission(Uri uri, final int modeFlags, int userId) { 8136 enforceNotIsolatedCaller("releasePersistableUriPermission"); 8137 8138 Preconditions.checkFlagsArgument(modeFlags, 8139 Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION); 8140 8141 synchronized (this) { 8142 final int callingUid = Binder.getCallingUid(); 8143 boolean persistChanged = false; 8144 8145 UriPermission exactPerm = findUriPermissionLocked(callingUid, 8146 new GrantUri(userId, uri, false)); 8147 UriPermission prefixPerm = findUriPermissionLocked(callingUid, 8148 new GrantUri(userId, uri, true)); 8149 if (exactPerm == null && prefixPerm == null) { 8150 throw new SecurityException("No permission grants found for UID " + callingUid 8151 + " and Uri " + uri.toSafeString()); 8152 } 8153 8154 if (exactPerm != null) { 8155 persistChanged |= exactPerm.releasePersistableModes(modeFlags); 8156 removeUriPermissionIfNeededLocked(exactPerm); 8157 } 8158 if (prefixPerm != null) { 8159 persistChanged |= prefixPerm.releasePersistableModes(modeFlags); 8160 removeUriPermissionIfNeededLocked(prefixPerm); 8161 } 8162 8163 if (persistChanged) { 8164 schedulePersistUriGrants(); 8165 } 8166 } 8167 } 8168 8169 /** 8170 * Prune any older {@link UriPermission} for the given UID until outstanding 8171 * persisted grants are below {@link #MAX_PERSISTED_URI_GRANTS}. 8172 * 8173 * @return if any mutations occured that require persisting. 8174 */ maybePrunePersistedUriGrantsLocked(int uid)8175 private boolean maybePrunePersistedUriGrantsLocked(int uid) { 8176 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(uid); 8177 if (perms == null) return false; 8178 if (perms.size() < MAX_PERSISTED_URI_GRANTS) return false; 8179 8180 final ArrayList<UriPermission> persisted = Lists.newArrayList(); 8181 for (UriPermission perm : perms.values()) { 8182 if (perm.persistedModeFlags != 0) { 8183 persisted.add(perm); 8184 } 8185 } 8186 8187 final int trimCount = persisted.size() - MAX_PERSISTED_URI_GRANTS; 8188 if (trimCount <= 0) return false; 8189 8190 Collections.sort(persisted, new UriPermission.PersistedTimeComparator()); 8191 for (int i = 0; i < trimCount; i++) { 8192 final UriPermission perm = persisted.get(i); 8193 8194 if (DEBUG_URI_PERMISSION) Slog.v(TAG_URI_PERMISSION, 8195 "Trimming grant created at " + perm.persistedCreateTime); 8196 8197 perm.releasePersistableModes(~0); 8198 removeUriPermissionIfNeededLocked(perm); 8199 } 8200 8201 return true; 8202 } 8203 8204 @Override getPersistedUriPermissions( String packageName, boolean incoming)8205 public ParceledListSlice<android.content.UriPermission> getPersistedUriPermissions( 8206 String packageName, boolean incoming) { 8207 enforceNotIsolatedCaller("getPersistedUriPermissions"); 8208 Preconditions.checkNotNull(packageName, "packageName"); 8209 8210 final int callingUid = Binder.getCallingUid(); 8211 final IPackageManager pm = AppGlobals.getPackageManager(); 8212 try { 8213 final int packageUid = pm.getPackageUid(packageName, UserHandle.getUserId(callingUid)); 8214 if (packageUid != callingUid) { 8215 throw new SecurityException( 8216 "Package " + packageName + " does not belong to calling UID " + callingUid); 8217 } 8218 } catch (RemoteException e) { 8219 throw new SecurityException("Failed to verify package name ownership"); 8220 } 8221 8222 final ArrayList<android.content.UriPermission> result = Lists.newArrayList(); 8223 synchronized (this) { 8224 if (incoming) { 8225 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get( 8226 callingUid); 8227 if (perms == null) { 8228 Slog.w(TAG, "No permission grants found for " + packageName); 8229 } else { 8230 for (UriPermission perm : perms.values()) { 8231 if (packageName.equals(perm.targetPkg) && perm.persistedModeFlags != 0) { 8232 result.add(perm.buildPersistedPublicApiObject()); 8233 } 8234 } 8235 } 8236 } else { 8237 final int size = mGrantedUriPermissions.size(); 8238 for (int i = 0; i < size; i++) { 8239 final ArrayMap<GrantUri, UriPermission> perms = 8240 mGrantedUriPermissions.valueAt(i); 8241 for (UriPermission perm : perms.values()) { 8242 if (packageName.equals(perm.sourcePkg) && perm.persistedModeFlags != 0) { 8243 result.add(perm.buildPersistedPublicApiObject()); 8244 } 8245 } 8246 } 8247 } 8248 } 8249 return new ParceledListSlice<android.content.UriPermission>(result); 8250 } 8251 8252 @Override showWaitingForDebugger(IApplicationThread who, boolean waiting)8253 public void showWaitingForDebugger(IApplicationThread who, boolean waiting) { 8254 synchronized (this) { 8255 ProcessRecord app = 8256 who != null ? getRecordForAppLocked(who) : null; 8257 if (app == null) return; 8258 8259 Message msg = Message.obtain(); 8260 msg.what = WAIT_FOR_DEBUGGER_MSG; 8261 msg.obj = app; 8262 msg.arg1 = waiting ? 1 : 0; 8263 mUiHandler.sendMessage(msg); 8264 } 8265 } 8266 8267 @Override getMemoryInfo(ActivityManager.MemoryInfo outInfo)8268 public void getMemoryInfo(ActivityManager.MemoryInfo outInfo) { 8269 final long homeAppMem = mProcessList.getMemLevel(ProcessList.HOME_APP_ADJ); 8270 final long cachedAppMem = mProcessList.getMemLevel(ProcessList.CACHED_APP_MIN_ADJ); 8271 outInfo.availMem = Process.getFreeMemory(); 8272 outInfo.totalMem = Process.getTotalMemory(); 8273 outInfo.threshold = homeAppMem; 8274 outInfo.lowMemory = outInfo.availMem < (homeAppMem + ((cachedAppMem-homeAppMem)/2)); 8275 outInfo.hiddenAppThreshold = cachedAppMem; 8276 outInfo.secondaryServerThreshold = mProcessList.getMemLevel( 8277 ProcessList.SERVICE_ADJ); 8278 outInfo.visibleAppThreshold = mProcessList.getMemLevel( 8279 ProcessList.VISIBLE_APP_ADJ); 8280 outInfo.foregroundAppThreshold = mProcessList.getMemLevel( 8281 ProcessList.FOREGROUND_APP_ADJ); 8282 } 8283 8284 // ========================================================= 8285 // TASK MANAGEMENT 8286 // ========================================================= 8287 8288 @Override 8289 public List<IAppTask> getAppTasks(String callingPackage) { 8290 int callingUid = Binder.getCallingUid(); 8291 long ident = Binder.clearCallingIdentity(); 8292 8293 synchronized(this) { 8294 ArrayList<IAppTask> list = new ArrayList<IAppTask>(); 8295 try { 8296 if (DEBUG_ALL) Slog.v(TAG, "getAppTasks"); 8297 8298 final int N = mRecentTasks.size(); 8299 for (int i = 0; i < N; i++) { 8300 TaskRecord tr = mRecentTasks.get(i); 8301 // Skip tasks that do not match the caller. We don't need to verify 8302 // callingPackage, because we are also limiting to callingUid and know 8303 // that will limit to the correct security sandbox. 8304 if (tr.effectiveUid != callingUid) { 8305 continue; 8306 } 8307 Intent intent = tr.getBaseIntent(); 8308 if (intent == null || 8309 !callingPackage.equals(intent.getComponent().getPackageName())) { 8310 continue; 8311 } 8312 ActivityManager.RecentTaskInfo taskInfo = 8313 createRecentTaskInfoFromTaskRecord(tr); 8314 AppTaskImpl taskImpl = new AppTaskImpl(taskInfo.persistentId, callingUid); 8315 list.add(taskImpl); 8316 } 8317 } finally { 8318 Binder.restoreCallingIdentity(ident); 8319 } 8320 return list; 8321 } 8322 } 8323 8324 @Override 8325 public List<RunningTaskInfo> getTasks(int maxNum, int flags) { 8326 final int callingUid = Binder.getCallingUid(); 8327 ArrayList<RunningTaskInfo> list = new ArrayList<RunningTaskInfo>(); 8328 8329 synchronized(this) { 8330 if (DEBUG_ALL) Slog.v( 8331 TAG, "getTasks: max=" + maxNum + ", flags=" + flags); 8332 8333 final boolean allowed = isGetTasksAllowed("getTasks", Binder.getCallingPid(), 8334 callingUid); 8335 8336 // TODO: Improve with MRU list from all ActivityStacks. 8337 mStackSupervisor.getTasksLocked(maxNum, list, callingUid, allowed); 8338 } 8339 8340 return list; 8341 } 8342 8343 /** 8344 * Creates a new RecentTaskInfo from a TaskRecord. 8345 */ 8346 private ActivityManager.RecentTaskInfo createRecentTaskInfoFromTaskRecord(TaskRecord tr) { 8347 // Update the task description to reflect any changes in the task stack 8348 tr.updateTaskDescription(); 8349 8350 // Compose the recent task info 8351 ActivityManager.RecentTaskInfo rti = new ActivityManager.RecentTaskInfo(); 8352 rti.id = tr.getTopActivity() == null ? INVALID_TASK_ID : tr.taskId; 8353 rti.persistentId = tr.taskId; 8354 rti.baseIntent = new Intent(tr.getBaseIntent()); 8355 rti.origActivity = tr.origActivity; 8356 rti.description = tr.lastDescription; 8357 rti.stackId = tr.stack != null ? tr.stack.mStackId : -1; 8358 rti.userId = tr.userId; 8359 rti.taskDescription = new ActivityManager.TaskDescription(tr.lastTaskDescription); 8360 rti.firstActiveTime = tr.firstActiveTime; 8361 rti.lastActiveTime = tr.lastActiveTime; 8362 rti.affiliatedTaskId = tr.mAffiliatedTaskId; 8363 rti.affiliatedTaskColor = tr.mAffiliatedTaskColor; 8364 rti.numActivities = 0; 8365 8366 ActivityRecord base = null; 8367 ActivityRecord top = null; 8368 ActivityRecord tmp; 8369 8370 for (int i = tr.mActivities.size() - 1; i >= 0; --i) { 8371 tmp = tr.mActivities.get(i); 8372 if (tmp.finishing) { 8373 continue; 8374 } 8375 base = tmp; 8376 if (top == null || (top.state == ActivityState.INITIALIZING)) { 8377 top = base; 8378 } 8379 rti.numActivities++; 8380 } 8381 8382 rti.baseActivity = (base != null) ? base.intent.getComponent() : null; 8383 rti.topActivity = (top != null) ? top.intent.getComponent() : null; 8384 8385 return rti; 8386 } 8387 8388 private boolean isGetTasksAllowed(String caller, int callingPid, int callingUid) { 8389 boolean allowed = checkPermission(android.Manifest.permission.REAL_GET_TASKS, 8390 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED; 8391 if (!allowed) { 8392 if (checkPermission(android.Manifest.permission.GET_TASKS, 8393 callingPid, callingUid) == PackageManager.PERMISSION_GRANTED) { 8394 // Temporary compatibility: some existing apps on the system image may 8395 // still be requesting the old permission and not switched to the new 8396 // one; if so, we'll still allow them full access. This means we need 8397 // to see if they are holding the old permission and are a system app. 8398 try { 8399 if (AppGlobals.getPackageManager().isUidPrivileged(callingUid)) { 8400 allowed = true; 8401 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid 8402 + " is using old GET_TASKS but privileged; allowing"); 8403 } 8404 } catch (RemoteException e) { 8405 } 8406 } 8407 } 8408 if (!allowed) { 8409 if (DEBUG_TASKS) Slog.w(TAG, caller + ": caller " + callingUid 8410 + " does not hold REAL_GET_TASKS; limiting output"); 8411 } 8412 return allowed; 8413 } 8414 8415 @Override 8416 public List<ActivityManager.RecentTaskInfo> getRecentTasks(int maxNum, int flags, int userId) { 8417 final int callingUid = Binder.getCallingUid(); 8418 userId = handleIncomingUser(Binder.getCallingPid(), callingUid, userId, 8419 false, ALLOW_FULL_ONLY, "getRecentTasks", null); 8420 8421 final boolean includeProfiles = (flags & ActivityManager.RECENT_INCLUDE_PROFILES) != 0; 8422 final boolean withExcluded = (flags&ActivityManager.RECENT_WITH_EXCLUDED) != 0; 8423 synchronized (this) { 8424 final boolean allowed = isGetTasksAllowed("getRecentTasks", Binder.getCallingPid(), 8425 callingUid); 8426 final boolean detailed = checkCallingPermission( 8427 android.Manifest.permission.GET_DETAILED_TASKS) 8428 == PackageManager.PERMISSION_GRANTED; 8429 8430 final int recentsCount = mRecentTasks.size(); 8431 ArrayList<ActivityManager.RecentTaskInfo> res = 8432 new ArrayList<>(maxNum < recentsCount ? maxNum : recentsCount); 8433 8434 final Set<Integer> includedUsers; 8435 if (includeProfiles) { 8436 includedUsers = getProfileIdsLocked(userId); 8437 } else { 8438 includedUsers = new HashSet<>(); 8439 } 8440 includedUsers.add(Integer.valueOf(userId)); 8441 8442 for (int i = 0; i < recentsCount && maxNum > 0; i++) { 8443 TaskRecord tr = mRecentTasks.get(i); 8444 // Only add calling user or related users recent tasks 8445 if (!includedUsers.contains(Integer.valueOf(tr.userId))) { 8446 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not user: " + tr); 8447 continue; 8448 } 8449 8450 // Return the entry if desired by the caller. We always return 8451 // the first entry, because callers always expect this to be the 8452 // foreground app. We may filter others if the caller has 8453 // not supplied RECENT_WITH_EXCLUDED and there is some reason 8454 // we should exclude the entry. 8455 8456 if (i == 0 8457 || withExcluded 8458 || (tr.intent == null) 8459 || ((tr.intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) 8460 == 0)) { 8461 if (!allowed) { 8462 // If the caller doesn't have the GET_TASKS permission, then only 8463 // allow them to see a small subset of tasks -- their own and home. 8464 if (!tr.isHomeTask() && tr.effectiveUid != callingUid) { 8465 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Skipping, not allowed: " + tr); 8466 continue; 8467 } 8468 } 8469 if ((flags & ActivityManager.RECENT_IGNORE_HOME_STACK_TASKS) != 0) { 8470 if (tr.stack != null && tr.stack.isHomeStack()) { 8471 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 8472 "Skipping, home stack task: " + tr); 8473 continue; 8474 } 8475 } 8476 if (tr.autoRemoveRecents && tr.getTopActivity() == null) { 8477 // Don't include auto remove tasks that are finished or finishing. 8478 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 8479 "Skipping, auto-remove without activity: " + tr); 8480 continue; 8481 } 8482 if ((flags&ActivityManager.RECENT_IGNORE_UNAVAILABLE) != 0 8483 && !tr.isAvailable) { 8484 if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, 8485 "Skipping, unavail real act: " + tr); 8486 continue; 8487 } 8488 8489 ActivityManager.RecentTaskInfo rti = createRecentTaskInfoFromTaskRecord(tr); 8490 if (!detailed) { 8491 rti.baseIntent.replaceExtras((Bundle)null); 8492 } 8493 8494 res.add(rti); 8495 maxNum--; 8496 } 8497 } 8498 return res; 8499 } 8500 } 8501 8502 @Override 8503 public ActivityManager.TaskThumbnail getTaskThumbnail(int id) { 8504 synchronized (this) { 8505 enforceCallingPermission(android.Manifest.permission.READ_FRAME_BUFFER, 8506 "getTaskThumbnail()"); 8507 TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(id, false); 8508 if (tr != null) { 8509 return tr.getTaskThumbnailLocked(); 8510 } 8511 } 8512 return null; 8513 } 8514 8515 @Override 8516 public int addAppTask(IBinder activityToken, Intent intent, 8517 ActivityManager.TaskDescription description, Bitmap thumbnail) throws RemoteException { 8518 final int callingUid = Binder.getCallingUid(); 8519 final long callingIdent = Binder.clearCallingIdentity(); 8520 8521 try { 8522 synchronized (this) { 8523 ActivityRecord r = ActivityRecord.isInStackLocked(activityToken); 8524 if (r == null) { 8525 throw new IllegalArgumentException("Activity does not exist; token=" 8526 + activityToken); 8527 } 8528 ComponentName comp = intent.getComponent(); 8529 if (comp == null) { 8530 throw new IllegalArgumentException("Intent " + intent 8531 + " must specify explicit component"); 8532 } 8533 if (thumbnail.getWidth() != mThumbnailWidth 8534 || thumbnail.getHeight() != mThumbnailHeight) { 8535 throw new IllegalArgumentException("Bad thumbnail size: got " 8536 + thumbnail.getWidth() + "x" + thumbnail.getHeight() + ", require " 8537 + mThumbnailWidth + "x" + mThumbnailHeight); 8538 } 8539 if (intent.getSelector() != null) { 8540 intent.setSelector(null); 8541 } 8542 if (intent.getSourceBounds() != null) { 8543 intent.setSourceBounds(null); 8544 } 8545 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0) { 8546 if ((intent.getFlags()&Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS) == 0) { 8547 // The caller has added this as an auto-remove task... that makes no 8548 // sense, so turn off auto-remove. 8549 intent.addFlags(Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS); 8550 } 8551 } else if ((intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { 8552 // Must be a new task. 8553 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 8554 } 8555 if (!comp.equals(mLastAddedTaskComponent) || callingUid != mLastAddedTaskUid) { 8556 mLastAddedTaskActivity = null; 8557 } 8558 ActivityInfo ainfo = mLastAddedTaskActivity; 8559 if (ainfo == null) { 8560 ainfo = mLastAddedTaskActivity = AppGlobals.getPackageManager().getActivityInfo( 8561 comp, 0, UserHandle.getUserId(callingUid)); 8562 if (ainfo.applicationInfo.uid != callingUid) { 8563 throw new SecurityException( 8564 "Can't add task for another application: target uid=" 8565 + ainfo.applicationInfo.uid + ", calling uid=" + callingUid); 8566 } 8567 } 8568 8569 TaskRecord task = new TaskRecord(this, mStackSupervisor.getNextTaskId(), ainfo, 8570 intent, description); 8571 8572 int trimIdx = mRecentTasks.trimForTaskLocked(task, false); 8573 if (trimIdx >= 0) { 8574 // If this would have caused a trim, then we'll abort because that 8575 // means it would be added at the end of the list but then just removed. 8576 return INVALID_TASK_ID; 8577 } 8578 8579 final int N = mRecentTasks.size(); 8580 if (N >= (ActivityManager.getMaxRecentTasksStatic()-1)) { 8581 final TaskRecord tr = mRecentTasks.remove(N - 1); 8582 tr.removedFromRecents(); 8583 } 8584 8585 task.inRecents = true; 8586 mRecentTasks.add(task); 8587 r.task.stack.addTask(task, false, false); 8588 8589 task.setLastThumbnail(thumbnail); 8590 task.freeLastThumbnail(); 8591 8592 return task.taskId; 8593 } 8594 } finally { 8595 Binder.restoreCallingIdentity(callingIdent); 8596 } 8597 } 8598 8599 @Override getAppTaskThumbnailSize()8600 public Point getAppTaskThumbnailSize() { 8601 synchronized (this) { 8602 return new Point(mThumbnailWidth, mThumbnailHeight); 8603 } 8604 } 8605 8606 @Override setTaskDescription(IBinder token, ActivityManager.TaskDescription td)8607 public void setTaskDescription(IBinder token, ActivityManager.TaskDescription td) { 8608 synchronized (this) { 8609 ActivityRecord r = ActivityRecord.isInStackLocked(token); 8610 if (r != null) { 8611 r.setTaskDescription(td); 8612 r.task.updateTaskDescription(); 8613 } 8614 } 8615 } 8616 8617 @Override setTaskResizeable(int taskId, boolean resizeable)8618 public void setTaskResizeable(int taskId, boolean resizeable) { 8619 synchronized (this) { 8620 TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId, false); 8621 if (task == null) { 8622 Slog.w(TAG, "setTaskResizeable: taskId=" + taskId + " not found"); 8623 return; 8624 } 8625 if (task.mResizeable != resizeable) { 8626 task.mResizeable = resizeable; 8627 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 8628 mStackSupervisor.resumeTopActivitiesLocked(); 8629 } 8630 } 8631 } 8632 8633 @Override resizeTask(int taskId, Rect bounds)8634 public void resizeTask(int taskId, Rect bounds) { 8635 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8636 "resizeTask()"); 8637 long ident = Binder.clearCallingIdentity(); 8638 try { 8639 synchronized (this) { 8640 TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 8641 if (task == null) { 8642 Slog.w(TAG, "resizeTask: taskId=" + taskId + " not found"); 8643 return; 8644 } 8645 mStackSupervisor.resizeTaskLocked(task, bounds); 8646 } 8647 } finally { 8648 Binder.restoreCallingIdentity(ident); 8649 } 8650 } 8651 8652 @Override getTaskDescriptionIcon(String filename)8653 public Bitmap getTaskDescriptionIcon(String filename) { 8654 if (!FileUtils.isValidExtFilename(filename) 8655 || !filename.contains(ActivityRecord.ACTIVITY_ICON_SUFFIX)) { 8656 throw new IllegalArgumentException("Bad filename: " + filename); 8657 } 8658 return mTaskPersister.getTaskDescriptionIcon(filename); 8659 } 8660 8661 @Override startInPlaceAnimationOnFrontMostApplication(ActivityOptions opts)8662 public void startInPlaceAnimationOnFrontMostApplication(ActivityOptions opts) 8663 throws RemoteException { 8664 if (opts.getAnimationType() != ActivityOptions.ANIM_CUSTOM_IN_PLACE || 8665 opts.getCustomInPlaceResId() == 0) { 8666 throw new IllegalArgumentException("Expected in-place ActivityOption " + 8667 "with valid animation"); 8668 } 8669 mWindowManager.prepareAppTransition(AppTransition.TRANSIT_TASK_IN_PLACE, false); 8670 mWindowManager.overridePendingAppTransitionInPlace(opts.getPackageName(), 8671 opts.getCustomInPlaceResId()); 8672 mWindowManager.executeAppTransition(); 8673 } 8674 cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess)8675 private void cleanUpRemovedTaskLocked(TaskRecord tr, boolean killProcess) { 8676 mRecentTasks.remove(tr); 8677 tr.removedFromRecents(); 8678 ComponentName component = tr.getBaseIntent().getComponent(); 8679 if (component == null) { 8680 Slog.w(TAG, "No component for base intent of task: " + tr); 8681 return; 8682 } 8683 8684 // Find any running services associated with this app and stop if needed. 8685 mServices.cleanUpRemovedTaskLocked(tr, component, new Intent(tr.getBaseIntent())); 8686 8687 if (!killProcess) { 8688 return; 8689 } 8690 8691 // Determine if the process(es) for this task should be killed. 8692 final String pkg = component.getPackageName(); 8693 ArrayList<ProcessRecord> procsToKill = new ArrayList<>(); 8694 ArrayMap<String, SparseArray<ProcessRecord>> pmap = mProcessNames.getMap(); 8695 for (int i = 0; i < pmap.size(); i++) { 8696 8697 SparseArray<ProcessRecord> uids = pmap.valueAt(i); 8698 for (int j = 0; j < uids.size(); j++) { 8699 ProcessRecord proc = uids.valueAt(j); 8700 if (proc.userId != tr.userId) { 8701 // Don't kill process for a different user. 8702 continue; 8703 } 8704 if (proc == mHomeProcess) { 8705 // Don't kill the home process along with tasks from the same package. 8706 continue; 8707 } 8708 if (!proc.pkgList.containsKey(pkg)) { 8709 // Don't kill process that is not associated with this task. 8710 continue; 8711 } 8712 8713 for (int k = 0; k < proc.activities.size(); k++) { 8714 TaskRecord otherTask = proc.activities.get(k).task; 8715 if (tr.taskId != otherTask.taskId && otherTask.inRecents) { 8716 // Don't kill process(es) that has an activity in a different task that is 8717 // also in recents. 8718 return; 8719 } 8720 } 8721 8722 if (proc.foregroundServices) { 8723 // Don't kill process(es) with foreground service. 8724 return; 8725 } 8726 8727 // Add process to kill list. 8728 procsToKill.add(proc); 8729 } 8730 } 8731 8732 // Kill the running processes. 8733 for (int i = 0; i < procsToKill.size(); i++) { 8734 ProcessRecord pr = procsToKill.get(i); 8735 if (pr.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 8736 && pr.curReceiver == null) { 8737 pr.kill("remove task", true); 8738 } else { 8739 // We delay killing processes that are not in the background or running a receiver. 8740 pr.waitingToKill = "remove task"; 8741 } 8742 } 8743 } 8744 removeTasksByPackageNameLocked(String packageName, int userId)8745 private void removeTasksByPackageNameLocked(String packageName, int userId) { 8746 // Remove all tasks with activities in the specified package from the list of recent tasks 8747 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 8748 TaskRecord tr = mRecentTasks.get(i); 8749 if (tr.userId != userId) continue; 8750 8751 ComponentName cn = tr.intent.getComponent(); 8752 if (cn != null && cn.getPackageName().equals(packageName)) { 8753 // If the package name matches, remove the task. 8754 removeTaskByIdLocked(tr.taskId, true); 8755 } 8756 } 8757 } 8758 cleanupDisabledPackageTasksLocked(String packageName, Set<String> filterByClasses, int userId)8759 private void cleanupDisabledPackageTasksLocked(String packageName, Set<String> filterByClasses, 8760 int userId) { 8761 8762 for (int i = mRecentTasks.size() - 1; i >= 0; i--) { 8763 TaskRecord tr = mRecentTasks.get(i); 8764 if (userId != UserHandle.USER_ALL && tr.userId != userId) { 8765 continue; 8766 } 8767 8768 ComponentName cn = tr.intent.getComponent(); 8769 final boolean sameComponent = cn != null && cn.getPackageName().equals(packageName) 8770 && (filterByClasses == null || filterByClasses.contains(cn.getClassName())); 8771 if (sameComponent) { 8772 removeTaskByIdLocked(tr.taskId, false); 8773 } 8774 } 8775 } 8776 8777 /** 8778 * Removes the task with the specified task id. 8779 * 8780 * @param taskId Identifier of the task to be removed. 8781 * @param killProcess Kill any process associated with the task if possible. 8782 * @return Returns true if the given task was found and removed. 8783 */ removeTaskByIdLocked(int taskId, boolean killProcess)8784 private boolean removeTaskByIdLocked(int taskId, boolean killProcess) { 8785 TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(taskId, false); 8786 if (tr != null) { 8787 tr.removeTaskActivitiesLocked(); 8788 cleanUpRemovedTaskLocked(tr, killProcess); 8789 if (tr.isPersistable) { 8790 notifyTaskPersisterLocked(null, true); 8791 } 8792 return true; 8793 } 8794 Slog.w(TAG, "Request to remove task ignored for non-existent task " + taskId); 8795 return false; 8796 } 8797 8798 @Override removeTask(int taskId)8799 public boolean removeTask(int taskId) { 8800 synchronized (this) { 8801 enforceCallingPermission(android.Manifest.permission.REMOVE_TASKS, 8802 "removeTask()"); 8803 long ident = Binder.clearCallingIdentity(); 8804 try { 8805 return removeTaskByIdLocked(taskId, true); 8806 } finally { 8807 Binder.restoreCallingIdentity(ident); 8808 } 8809 } 8810 } 8811 8812 /** 8813 * TODO: Add mController hook 8814 */ 8815 @Override moveTaskToFront(int taskId, int flags, Bundle options)8816 public void moveTaskToFront(int taskId, int flags, Bundle options) { 8817 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, "moveTaskToFront()"); 8818 8819 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToFront: moving taskId=" + taskId); 8820 synchronized(this) { 8821 moveTaskToFrontLocked(taskId, flags, options); 8822 } 8823 } 8824 moveTaskToFrontLocked(int taskId, int flags, Bundle options)8825 void moveTaskToFrontLocked(int taskId, int flags, Bundle options) { 8826 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 8827 Binder.getCallingUid(), -1, -1, "Task to front")) { 8828 ActivityOptions.abort(options); 8829 return; 8830 } 8831 final long origId = Binder.clearCallingIdentity(); 8832 try { 8833 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 8834 if (task == null) { 8835 Slog.d(TAG, "Could not find task for id: "+ taskId); 8836 return; 8837 } 8838 if (mStackSupervisor.isLockTaskModeViolation(task)) { 8839 mStackSupervisor.showLockTaskToast(); 8840 Slog.e(TAG, "moveTaskToFront: Attempt to violate Lock Task Mode"); 8841 return; 8842 } 8843 final ActivityRecord prev = mStackSupervisor.topRunningActivityLocked(); 8844 if (prev != null && prev.isRecentsActivity()) { 8845 task.setTaskToReturnTo(ActivityRecord.RECENTS_ACTIVITY_TYPE); 8846 } 8847 mStackSupervisor.findTaskToMoveToFrontLocked(task, flags, options, "moveTaskToFront"); 8848 } finally { 8849 Binder.restoreCallingIdentity(origId); 8850 } 8851 ActivityOptions.abort(options); 8852 } 8853 8854 /** 8855 * Moves an activity, and all of the other activities within the same task, to the bottom 8856 * of the history stack. The activity's order within the task is unchanged. 8857 * 8858 * @param token A reference to the activity we wish to move 8859 * @param nonRoot If false then this only works if the activity is the root 8860 * of a task; if true it will work for any activity in a task. 8861 * @return Returns true if the move completed, false if not. 8862 */ 8863 @Override moveActivityTaskToBack(IBinder token, boolean nonRoot)8864 public boolean moveActivityTaskToBack(IBinder token, boolean nonRoot) { 8865 enforceNotIsolatedCaller("moveActivityTaskToBack"); 8866 synchronized(this) { 8867 final long origId = Binder.clearCallingIdentity(); 8868 try { 8869 int taskId = ActivityRecord.getTaskForActivityLocked(token, !nonRoot); 8870 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 8871 if (task != null) { 8872 if (mStackSupervisor.isLockedTask(task)) { 8873 mStackSupervisor.showLockTaskToast(); 8874 return false; 8875 } 8876 return ActivityRecord.getStackLocked(token).moveTaskToBackLocked(taskId); 8877 } 8878 } finally { 8879 Binder.restoreCallingIdentity(origId); 8880 } 8881 } 8882 return false; 8883 } 8884 8885 @Override moveTaskBackwards(int task)8886 public void moveTaskBackwards(int task) { 8887 enforceCallingPermission(android.Manifest.permission.REORDER_TASKS, 8888 "moveTaskBackwards()"); 8889 8890 synchronized(this) { 8891 if (!checkAppSwitchAllowedLocked(Binder.getCallingPid(), 8892 Binder.getCallingUid(), -1, -1, "Task backwards")) { 8893 return; 8894 } 8895 final long origId = Binder.clearCallingIdentity(); 8896 moveTaskBackwardsLocked(task); 8897 Binder.restoreCallingIdentity(origId); 8898 } 8899 } 8900 moveTaskBackwardsLocked(int task)8901 private final void moveTaskBackwardsLocked(int task) { 8902 Slog.e(TAG, "moveTaskBackwards not yet implemented!"); 8903 } 8904 8905 @Override createVirtualActivityContainer(IBinder parentActivityToken, IActivityContainerCallback callback)8906 public IActivityContainer createVirtualActivityContainer(IBinder parentActivityToken, 8907 IActivityContainerCallback callback) throws RemoteException { 8908 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8909 "createActivityContainer()"); 8910 synchronized (this) { 8911 if (parentActivityToken == null) { 8912 throw new IllegalArgumentException("parent token must not be null"); 8913 } 8914 ActivityRecord r = ActivityRecord.forTokenLocked(parentActivityToken); 8915 if (r == null) { 8916 return null; 8917 } 8918 if (callback == null) { 8919 throw new IllegalArgumentException("callback must not be null"); 8920 } 8921 return mStackSupervisor.createVirtualActivityContainer(r, callback); 8922 } 8923 } 8924 8925 @Override deleteActivityContainer(IActivityContainer container)8926 public void deleteActivityContainer(IActivityContainer container) throws RemoteException { 8927 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8928 "deleteActivityContainer()"); 8929 synchronized (this) { 8930 mStackSupervisor.deleteActivityContainer(container); 8931 } 8932 } 8933 8934 @Override createStackOnDisplay(int displayId)8935 public IActivityContainer createStackOnDisplay(int displayId) throws RemoteException { 8936 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8937 "createStackOnDisplay()"); 8938 synchronized (this) { 8939 final int stackId = mStackSupervisor.getNextStackId(); 8940 final ActivityStack stack = mStackSupervisor.createStackOnDisplay(stackId, displayId); 8941 if (stack == null) { 8942 return null; 8943 } 8944 return stack.mActivityContainer; 8945 } 8946 } 8947 8948 @Override getActivityDisplayId(IBinder activityToken)8949 public int getActivityDisplayId(IBinder activityToken) throws RemoteException { 8950 synchronized (this) { 8951 ActivityStack stack = ActivityRecord.getStackLocked(activityToken); 8952 if (stack != null && stack.mActivityContainer.isAttachedLocked()) { 8953 return stack.mActivityContainer.getDisplayId(); 8954 } 8955 return Display.DEFAULT_DISPLAY; 8956 } 8957 } 8958 8959 @Override moveTaskToStack(int taskId, int stackId, boolean toTop)8960 public void moveTaskToStack(int taskId, int stackId, boolean toTop) { 8961 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8962 "moveTaskToStack()"); 8963 if (stackId == HOME_STACK_ID) { 8964 Slog.e(TAG, "moveTaskToStack: Attempt to move task " + taskId + " to home stack", 8965 new RuntimeException("here").fillInStackTrace()); 8966 } 8967 synchronized (this) { 8968 long ident = Binder.clearCallingIdentity(); 8969 try { 8970 if (DEBUG_STACK) Slog.d(TAG_STACK, "moveTaskToStack: moving task=" + taskId 8971 + " to stackId=" + stackId + " toTop=" + toTop); 8972 mStackSupervisor.moveTaskToStackLocked(taskId, stackId, toTop); 8973 } finally { 8974 Binder.restoreCallingIdentity(ident); 8975 } 8976 } 8977 } 8978 8979 @Override resizeStack(int stackId, Rect bounds)8980 public void resizeStack(int stackId, Rect bounds) { 8981 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8982 "resizeStack()"); 8983 long ident = Binder.clearCallingIdentity(); 8984 try { 8985 synchronized (this) { 8986 mStackSupervisor.resizeStackLocked(stackId, bounds); 8987 } 8988 } finally { 8989 Binder.restoreCallingIdentity(ident); 8990 } 8991 } 8992 8993 @Override getAllStackInfos()8994 public List<StackInfo> getAllStackInfos() { 8995 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 8996 "getAllStackInfos()"); 8997 long ident = Binder.clearCallingIdentity(); 8998 try { 8999 synchronized (this) { 9000 return mStackSupervisor.getAllStackInfosLocked(); 9001 } 9002 } finally { 9003 Binder.restoreCallingIdentity(ident); 9004 } 9005 } 9006 9007 @Override getStackInfo(int stackId)9008 public StackInfo getStackInfo(int stackId) { 9009 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 9010 "getStackInfo()"); 9011 long ident = Binder.clearCallingIdentity(); 9012 try { 9013 synchronized (this) { 9014 return mStackSupervisor.getStackInfoLocked(stackId); 9015 } 9016 } finally { 9017 Binder.restoreCallingIdentity(ident); 9018 } 9019 } 9020 9021 @Override isInHomeStack(int taskId)9022 public boolean isInHomeStack(int taskId) { 9023 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 9024 "getStackInfo()"); 9025 long ident = Binder.clearCallingIdentity(); 9026 try { 9027 synchronized (this) { 9028 TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(taskId, false); 9029 return tr != null && tr.stack != null && tr.stack.isHomeStack(); 9030 } 9031 } finally { 9032 Binder.restoreCallingIdentity(ident); 9033 } 9034 } 9035 9036 @Override getTaskForActivity(IBinder token, boolean onlyRoot)9037 public int getTaskForActivity(IBinder token, boolean onlyRoot) { 9038 synchronized(this) { 9039 return ActivityRecord.getTaskForActivityLocked(token, onlyRoot); 9040 } 9041 } 9042 9043 @Override updateDeviceOwner(String packageName)9044 public void updateDeviceOwner(String packageName) { 9045 final int callingUid = Binder.getCallingUid(); 9046 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 9047 throw new SecurityException("updateDeviceOwner called from non-system process"); 9048 } 9049 synchronized (this) { 9050 mDeviceOwnerName = packageName; 9051 } 9052 } 9053 9054 @Override updateLockTaskPackages(int userId, String[] packages)9055 public void updateLockTaskPackages(int userId, String[] packages) { 9056 final int callingUid = Binder.getCallingUid(); 9057 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 9058 throw new SecurityException("updateLockTaskPackage called from non-system process"); 9059 } 9060 synchronized (this) { 9061 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Whitelisting " + userId + ":" + 9062 Arrays.toString(packages)); 9063 mLockTaskPackages.put(userId, packages); 9064 mStackSupervisor.onLockTaskPackagesUpdatedLocked(); 9065 } 9066 } 9067 9068 startLockTaskModeLocked(TaskRecord task)9069 void startLockTaskModeLocked(TaskRecord task) { 9070 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "startLockTaskModeLocked: " + task); 9071 if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) { 9072 return; 9073 } 9074 9075 // isSystemInitiated is used to distinguish between locked and pinned mode, as pinned mode 9076 // is initiated by system after the pinning request was shown and locked mode is initiated 9077 // by an authorized app directly 9078 final int callingUid = Binder.getCallingUid(); 9079 boolean isSystemInitiated = callingUid == Process.SYSTEM_UID; 9080 long ident = Binder.clearCallingIdentity(); 9081 try { 9082 final ActivityStack stack = mStackSupervisor.getFocusedStack(); 9083 if (!isSystemInitiated) { 9084 task.mLockTaskUid = callingUid; 9085 if (task.mLockTaskAuth == LOCK_TASK_AUTH_PINNABLE) { 9086 // startLockTask() called by app and task mode is lockTaskModeDefault. 9087 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "Mode default, asking user"); 9088 StatusBarManagerInternal statusBarManager = 9089 LocalServices.getService(StatusBarManagerInternal.class); 9090 if (statusBarManager != null) { 9091 statusBarManager.showScreenPinningRequest(); 9092 } 9093 return; 9094 } 9095 9096 if (stack == null || task != stack.topTask()) { 9097 throw new IllegalArgumentException("Invalid task, not in foreground"); 9098 } 9099 } 9100 if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, isSystemInitiated ? "Locking pinned" : 9101 "Locking fully"); 9102 mStackSupervisor.setLockTaskModeLocked(task, isSystemInitiated ? 9103 ActivityManager.LOCK_TASK_MODE_PINNED : 9104 ActivityManager.LOCK_TASK_MODE_LOCKED, 9105 "startLockTask", true); 9106 } finally { 9107 Binder.restoreCallingIdentity(ident); 9108 } 9109 } 9110 9111 @Override startLockTaskMode(int taskId)9112 public void startLockTaskMode(int taskId) { 9113 synchronized (this) { 9114 final TaskRecord task = mStackSupervisor.anyTaskForIdLocked(taskId); 9115 if (task != null) { 9116 startLockTaskModeLocked(task); 9117 } 9118 } 9119 } 9120 9121 @Override startLockTaskMode(IBinder token)9122 public void startLockTaskMode(IBinder token) { 9123 synchronized (this) { 9124 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 9125 if (r == null) { 9126 return; 9127 } 9128 final TaskRecord task = r.task; 9129 if (task != null) { 9130 startLockTaskModeLocked(task); 9131 } 9132 } 9133 } 9134 9135 @Override startLockTaskModeOnCurrent()9136 public void startLockTaskModeOnCurrent() throws RemoteException { 9137 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 9138 "startLockTaskModeOnCurrent"); 9139 long ident = Binder.clearCallingIdentity(); 9140 try { 9141 synchronized (this) { 9142 ActivityRecord r = mStackSupervisor.topRunningActivityLocked(); 9143 if (r != null) { 9144 startLockTaskModeLocked(r.task); 9145 } 9146 } 9147 } finally { 9148 Binder.restoreCallingIdentity(ident); 9149 } 9150 } 9151 9152 @Override stopLockTaskMode()9153 public void stopLockTaskMode() { 9154 final TaskRecord lockTask = mStackSupervisor.getLockedTaskLocked(); 9155 if (lockTask == null) { 9156 // Our work here is done. 9157 return; 9158 } 9159 9160 final int callingUid = Binder.getCallingUid(); 9161 final int lockTaskUid = lockTask.mLockTaskUid; 9162 // Ensure the same caller for startLockTaskMode and stopLockTaskMode. 9163 // It is possible lockTaskMode was started by the system process because 9164 // android:lockTaskMode is set to a locking value in the application manifest instead of 9165 // the app calling startLockTaskMode. In this case {@link TaskRecord.mLockTaskUid} will 9166 // be 0, so we compare the callingUid to the {@link TaskRecord.effectiveUid} instead. 9167 if (getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_LOCKED && 9168 callingUid != lockTaskUid 9169 && (lockTaskUid != 0 9170 || (lockTaskUid == 0 && callingUid != lockTask.effectiveUid))) { 9171 throw new SecurityException("Invalid uid, expected " + lockTaskUid 9172 + " callingUid=" + callingUid + " effectiveUid=" + lockTask.effectiveUid); 9173 } 9174 9175 long ident = Binder.clearCallingIdentity(); 9176 try { 9177 Log.d(TAG, "stopLockTaskMode"); 9178 // Stop lock task 9179 synchronized (this) { 9180 mStackSupervisor.setLockTaskModeLocked(null, ActivityManager.LOCK_TASK_MODE_NONE, 9181 "stopLockTask", true); 9182 } 9183 TelecomManager tm = (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE); 9184 if (tm != null) { 9185 tm.showInCallScreen(false); 9186 } 9187 } finally { 9188 Binder.restoreCallingIdentity(ident); 9189 } 9190 } 9191 9192 @Override stopLockTaskModeOnCurrent()9193 public void stopLockTaskModeOnCurrent() throws RemoteException { 9194 enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS, 9195 "stopLockTaskModeOnCurrent"); 9196 long ident = Binder.clearCallingIdentity(); 9197 try { 9198 stopLockTaskMode(); 9199 } finally { 9200 Binder.restoreCallingIdentity(ident); 9201 } 9202 } 9203 9204 @Override isInLockTaskMode()9205 public boolean isInLockTaskMode() { 9206 return getLockTaskModeState() != ActivityManager.LOCK_TASK_MODE_NONE; 9207 } 9208 9209 @Override getLockTaskModeState()9210 public int getLockTaskModeState() { 9211 synchronized (this) { 9212 return mStackSupervisor.getLockTaskModeState(); 9213 } 9214 } 9215 9216 @Override showLockTaskEscapeMessage(IBinder token)9217 public void showLockTaskEscapeMessage(IBinder token) { 9218 synchronized (this) { 9219 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 9220 if (r == null) { 9221 return; 9222 } 9223 mStackSupervisor.showLockTaskEscapeMessageLocked(r.task); 9224 } 9225 } 9226 9227 // ========================================================= 9228 // CONTENT PROVIDERS 9229 // ========================================================= 9230 generateApplicationProvidersLocked(ProcessRecord app)9231 private final List<ProviderInfo> generateApplicationProvidersLocked(ProcessRecord app) { 9232 List<ProviderInfo> providers = null; 9233 try { 9234 ParceledListSlice<ProviderInfo> slice = AppGlobals.getPackageManager(). 9235 queryContentProviders(app.processName, app.uid, 9236 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS); 9237 providers = slice != null ? slice.getList() : null; 9238 } catch (RemoteException ex) { 9239 } 9240 if (DEBUG_MU) Slog.v(TAG_MU, 9241 "generateApplicationProvidersLocked, app.info.uid = " + app.uid); 9242 int userId = app.userId; 9243 if (providers != null) { 9244 int N = providers.size(); 9245 app.pubProviders.ensureCapacity(N + app.pubProviders.size()); 9246 for (int i=0; i<N; i++) { 9247 ProviderInfo cpi = 9248 (ProviderInfo)providers.get(i); 9249 boolean singleton = isSingleton(cpi.processName, cpi.applicationInfo, 9250 cpi.name, cpi.flags); 9251 if (singleton && UserHandle.getUserId(app.uid) != UserHandle.USER_OWNER) { 9252 // This is a singleton provider, but a user besides the 9253 // default user is asking to initialize a process it runs 9254 // in... well, no, it doesn't actually run in this process, 9255 // it runs in the process of the default user. Get rid of it. 9256 providers.remove(i); 9257 N--; 9258 i--; 9259 continue; 9260 } 9261 9262 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 9263 ContentProviderRecord cpr = mProviderMap.getProviderByClass(comp, userId); 9264 if (cpr == null) { 9265 cpr = new ContentProviderRecord(this, cpi, app.info, comp, singleton); 9266 mProviderMap.putProviderByClass(comp, cpr); 9267 } 9268 if (DEBUG_MU) Slog.v(TAG_MU, 9269 "generateApplicationProvidersLocked, cpi.uid = " + cpr.uid); 9270 app.pubProviders.put(cpi.name, cpr); 9271 if (!cpi.multiprocess || !"android".equals(cpi.packageName)) { 9272 // Don't add this if it is a platform component that is marked 9273 // to run in multiple processes, because this is actually 9274 // part of the framework so doesn't make sense to track as a 9275 // separate apk in the process. 9276 app.addPackage(cpi.applicationInfo.packageName, cpi.applicationInfo.versionCode, 9277 mProcessStats); 9278 } 9279 ensurePackageDexOpt(cpi.applicationInfo.packageName); 9280 } 9281 } 9282 return providers; 9283 } 9284 9285 /** 9286 * Check if {@link ProcessRecord} has a possible chance at accessing the 9287 * given {@link ProviderInfo}. Final permission checking is always done 9288 * in {@link ContentProvider}. 9289 */ checkContentProviderPermissionLocked( ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser)9290 private final String checkContentProviderPermissionLocked( 9291 ProviderInfo cpi, ProcessRecord r, int userId, boolean checkUser) { 9292 final int callingPid = (r != null) ? r.pid : Binder.getCallingPid(); 9293 final int callingUid = (r != null) ? r.uid : Binder.getCallingUid(); 9294 boolean checkedGrants = false; 9295 if (checkUser) { 9296 // Looking for cross-user grants before enforcing the typical cross-users permissions 9297 int tmpTargetUserId = unsafeConvertIncomingUser(userId); 9298 if (tmpTargetUserId != UserHandle.getUserId(callingUid)) { 9299 if (checkAuthorityGrants(callingUid, cpi, tmpTargetUserId, checkUser)) { 9300 return null; 9301 } 9302 checkedGrants = true; 9303 } 9304 userId = handleIncomingUser(callingPid, callingUid, userId, 9305 false, ALLOW_NON_FULL, 9306 "checkContentProviderPermissionLocked " + cpi.authority, null); 9307 if (userId != tmpTargetUserId) { 9308 // When we actually went to determine the final targer user ID, this ended 9309 // up different than our initial check for the authority. This is because 9310 // they had asked for USER_CURRENT_OR_SELF and we ended up switching to 9311 // SELF. So we need to re-check the grants again. 9312 checkedGrants = false; 9313 } 9314 } 9315 if (checkComponentPermission(cpi.readPermission, callingPid, callingUid, 9316 cpi.applicationInfo.uid, cpi.exported) 9317 == PackageManager.PERMISSION_GRANTED) { 9318 return null; 9319 } 9320 if (checkComponentPermission(cpi.writePermission, callingPid, callingUid, 9321 cpi.applicationInfo.uid, cpi.exported) 9322 == PackageManager.PERMISSION_GRANTED) { 9323 return null; 9324 } 9325 9326 PathPermission[] pps = cpi.pathPermissions; 9327 if (pps != null) { 9328 int i = pps.length; 9329 while (i > 0) { 9330 i--; 9331 PathPermission pp = pps[i]; 9332 String pprperm = pp.getReadPermission(); 9333 if (pprperm != null && checkComponentPermission(pprperm, callingPid, callingUid, 9334 cpi.applicationInfo.uid, cpi.exported) 9335 == PackageManager.PERMISSION_GRANTED) { 9336 return null; 9337 } 9338 String ppwperm = pp.getWritePermission(); 9339 if (ppwperm != null && checkComponentPermission(ppwperm, callingPid, callingUid, 9340 cpi.applicationInfo.uid, cpi.exported) 9341 == PackageManager.PERMISSION_GRANTED) { 9342 return null; 9343 } 9344 } 9345 } 9346 if (!checkedGrants && checkAuthorityGrants(callingUid, cpi, userId, checkUser)) { 9347 return null; 9348 } 9349 9350 String msg; 9351 if (!cpi.exported) { 9352 msg = "Permission Denial: opening provider " + cpi.name 9353 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 9354 + ", uid=" + callingUid + ") that is not exported from uid " 9355 + cpi.applicationInfo.uid; 9356 } else { 9357 msg = "Permission Denial: opening provider " + cpi.name 9358 + " from " + (r != null ? r : "(null)") + " (pid=" + callingPid 9359 + ", uid=" + callingUid + ") requires " 9360 + cpi.readPermission + " or " + cpi.writePermission; 9361 } 9362 Slog.w(TAG, msg); 9363 return msg; 9364 } 9365 9366 /** 9367 * Returns if the ContentProvider has granted a uri to callingUid 9368 */ checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser)9369 boolean checkAuthorityGrants(int callingUid, ProviderInfo cpi, int userId, boolean checkUser) { 9370 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.get(callingUid); 9371 if (perms != null) { 9372 for (int i=perms.size()-1; i>=0; i--) { 9373 GrantUri grantUri = perms.keyAt(i); 9374 if (grantUri.sourceUserId == userId || !checkUser) { 9375 if (matchesProvider(grantUri.uri, cpi)) { 9376 return true; 9377 } 9378 } 9379 } 9380 } 9381 return false; 9382 } 9383 9384 /** 9385 * Returns true if the uri authority is one of the authorities specified in the provider. 9386 */ matchesProvider(Uri uri, ProviderInfo cpi)9387 boolean matchesProvider(Uri uri, ProviderInfo cpi) { 9388 String uriAuth = uri.getAuthority(); 9389 String cpiAuth = cpi.authority; 9390 if (cpiAuth.indexOf(';') == -1) { 9391 return cpiAuth.equals(uriAuth); 9392 } 9393 String[] cpiAuths = cpiAuth.split(";"); 9394 int length = cpiAuths.length; 9395 for (int i = 0; i < length; i++) { 9396 if (cpiAuths[i].equals(uriAuth)) return true; 9397 } 9398 return false; 9399 } 9400 incProviderCountLocked(ProcessRecord r, final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable)9401 ContentProviderConnection incProviderCountLocked(ProcessRecord r, 9402 final ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 9403 if (r != null) { 9404 for (int i=0; i<r.conProviders.size(); i++) { 9405 ContentProviderConnection conn = r.conProviders.get(i); 9406 if (conn.provider == cpr) { 9407 if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER, 9408 "Adding provider requested by " 9409 + r.processName + " from process " 9410 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 9411 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 9412 if (stable) { 9413 conn.stableCount++; 9414 conn.numStableIncs++; 9415 } else { 9416 conn.unstableCount++; 9417 conn.numUnstableIncs++; 9418 } 9419 return conn; 9420 } 9421 } 9422 ContentProviderConnection conn = new ContentProviderConnection(cpr, r); 9423 if (stable) { 9424 conn.stableCount = 1; 9425 conn.numStableIncs = 1; 9426 } else { 9427 conn.unstableCount = 1; 9428 conn.numUnstableIncs = 1; 9429 } 9430 cpr.connections.add(conn); 9431 r.conProviders.add(conn); 9432 startAssociationLocked(r.uid, r.processName, cpr.uid, cpr.name, cpr.info.processName); 9433 return conn; 9434 } 9435 cpr.addExternalProcessHandleLocked(externalProcessToken); 9436 return null; 9437 } 9438 decProviderCountLocked(ContentProviderConnection conn, ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable)9439 boolean decProviderCountLocked(ContentProviderConnection conn, 9440 ContentProviderRecord cpr, IBinder externalProcessToken, boolean stable) { 9441 if (conn != null) { 9442 cpr = conn.provider; 9443 if (DEBUG_PROVIDER) Slog.v(TAG_PROVIDER, 9444 "Removing provider requested by " 9445 + conn.client.processName + " from process " 9446 + cpr.info.processName + ": " + cpr.name.flattenToShortString() 9447 + " scnt=" + conn.stableCount + " uscnt=" + conn.unstableCount); 9448 if (stable) { 9449 conn.stableCount--; 9450 } else { 9451 conn.unstableCount--; 9452 } 9453 if (conn.stableCount == 0 && conn.unstableCount == 0) { 9454 cpr.connections.remove(conn); 9455 conn.client.conProviders.remove(conn); 9456 stopAssociationLocked(conn.client.uid, conn.client.processName, cpr.uid, cpr.name); 9457 return true; 9458 } 9459 return false; 9460 } 9461 cpr.removeExternalProcessHandleLocked(externalProcessToken); 9462 return false; 9463 } 9464 checkTime(long startTime, String where)9465 private void checkTime(long startTime, String where) { 9466 long now = SystemClock.elapsedRealtime(); 9467 if ((now-startTime) > 1000) { 9468 // If we are taking more than a second, log about it. 9469 Slog.w(TAG, "Slow operation: " + (now-startTime) + "ms so far, now at " + where); 9470 } 9471 } 9472 getContentProviderImpl(IApplicationThread caller, String name, IBinder token, boolean stable, int userId)9473 private final ContentProviderHolder getContentProviderImpl(IApplicationThread caller, 9474 String name, IBinder token, boolean stable, int userId) { 9475 ContentProviderRecord cpr; 9476 ContentProviderConnection conn = null; 9477 ProviderInfo cpi = null; 9478 9479 synchronized(this) { 9480 long startTime = SystemClock.elapsedRealtime(); 9481 9482 ProcessRecord r = null; 9483 if (caller != null) { 9484 r = getRecordForAppLocked(caller); 9485 if (r == null) { 9486 throw new SecurityException( 9487 "Unable to find app for caller " + caller 9488 + " (pid=" + Binder.getCallingPid() 9489 + ") when getting content provider " + name); 9490 } 9491 } 9492 9493 boolean checkCrossUser = true; 9494 9495 checkTime(startTime, "getContentProviderImpl: getProviderByName"); 9496 9497 // First check if this content provider has been published... 9498 cpr = mProviderMap.getProviderByName(name, userId); 9499 // If that didn't work, check if it exists for user 0 and then 9500 // verify that it's a singleton provider before using it. 9501 if (cpr == null && userId != UserHandle.USER_OWNER) { 9502 cpr = mProviderMap.getProviderByName(name, UserHandle.USER_OWNER); 9503 if (cpr != null) { 9504 cpi = cpr.info; 9505 if (isSingleton(cpi.processName, cpi.applicationInfo, 9506 cpi.name, cpi.flags) 9507 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid)) { 9508 userId = UserHandle.USER_OWNER; 9509 checkCrossUser = false; 9510 } else { 9511 cpr = null; 9512 cpi = null; 9513 } 9514 } 9515 } 9516 9517 boolean providerRunning = cpr != null; 9518 if (providerRunning) { 9519 cpi = cpr.info; 9520 String msg; 9521 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 9522 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, checkCrossUser)) 9523 != null) { 9524 throw new SecurityException(msg); 9525 } 9526 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 9527 9528 if (r != null && cpr.canRunHere(r)) { 9529 // This provider has been published or is in the process 9530 // of being published... but it is also allowed to run 9531 // in the caller's process, so don't make a connection 9532 // and just let the caller instantiate its own instance. 9533 ContentProviderHolder holder = cpr.newHolder(null); 9534 // don't give caller the provider object, it needs 9535 // to make its own. 9536 holder.provider = null; 9537 return holder; 9538 } 9539 9540 final long origId = Binder.clearCallingIdentity(); 9541 9542 checkTime(startTime, "getContentProviderImpl: incProviderCountLocked"); 9543 9544 // In this case the provider instance already exists, so we can 9545 // return it right away. 9546 conn = incProviderCountLocked(r, cpr, token, stable); 9547 if (conn != null && (conn.stableCount+conn.unstableCount) == 1) { 9548 if (cpr.proc != null && r.setAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 9549 // If this is a perceptible app accessing the provider, 9550 // make sure to count it as being accessed and thus 9551 // back up on the LRU list. This is good because 9552 // content providers are often expensive to start. 9553 checkTime(startTime, "getContentProviderImpl: before updateLruProcess"); 9554 updateLruProcessLocked(cpr.proc, false, null); 9555 checkTime(startTime, "getContentProviderImpl: after updateLruProcess"); 9556 } 9557 } 9558 9559 if (cpr.proc != null) { 9560 if (false) { 9561 if (cpr.name.flattenToShortString().equals( 9562 "com.android.providers.calendar/.CalendarProvider2")) { 9563 Slog.v(TAG, "****************** KILLING " 9564 + cpr.name.flattenToShortString()); 9565 Process.killProcess(cpr.proc.pid); 9566 } 9567 } 9568 checkTime(startTime, "getContentProviderImpl: before updateOomAdj"); 9569 boolean success = updateOomAdjLocked(cpr.proc); 9570 maybeUpdateProviderUsageStatsLocked(r, cpr.info.packageName, name); 9571 checkTime(startTime, "getContentProviderImpl: after updateOomAdj"); 9572 if (DEBUG_PROVIDER) Slog.i(TAG_PROVIDER, "Adjust success: " + success); 9573 // NOTE: there is still a race here where a signal could be 9574 // pending on the process even though we managed to update its 9575 // adj level. Not sure what to do about this, but at least 9576 // the race is now smaller. 9577 if (!success) { 9578 // Uh oh... it looks like the provider's process 9579 // has been killed on us. We need to wait for a new 9580 // process to be started, and make sure its death 9581 // doesn't kill our process. 9582 Slog.i(TAG, "Existing provider " + cpr.name.flattenToShortString() 9583 + " is crashing; detaching " + r); 9584 boolean lastRef = decProviderCountLocked(conn, cpr, token, stable); 9585 checkTime(startTime, "getContentProviderImpl: before appDied"); 9586 appDiedLocked(cpr.proc); 9587 checkTime(startTime, "getContentProviderImpl: after appDied"); 9588 if (!lastRef) { 9589 // This wasn't the last ref our process had on 9590 // the provider... we have now been killed, bail. 9591 return null; 9592 } 9593 providerRunning = false; 9594 conn = null; 9595 } 9596 } 9597 9598 Binder.restoreCallingIdentity(origId); 9599 } 9600 9601 boolean singleton; 9602 if (!providerRunning) { 9603 try { 9604 checkTime(startTime, "getContentProviderImpl: before resolveContentProvider"); 9605 cpi = AppGlobals.getPackageManager(). 9606 resolveContentProvider(name, 9607 STOCK_PM_FLAGS | PackageManager.GET_URI_PERMISSION_PATTERNS, userId); 9608 checkTime(startTime, "getContentProviderImpl: after resolveContentProvider"); 9609 } catch (RemoteException ex) { 9610 } 9611 if (cpi == null) { 9612 return null; 9613 } 9614 // If the provider is a singleton AND 9615 // (it's a call within the same user || the provider is a 9616 // privileged app) 9617 // Then allow connecting to the singleton provider 9618 singleton = isSingleton(cpi.processName, cpi.applicationInfo, 9619 cpi.name, cpi.flags) 9620 && isValidSingletonCall(r.uid, cpi.applicationInfo.uid); 9621 if (singleton) { 9622 userId = UserHandle.USER_OWNER; 9623 } 9624 cpi.applicationInfo = getAppInfoForUser(cpi.applicationInfo, userId); 9625 checkTime(startTime, "getContentProviderImpl: got app info for user"); 9626 9627 String msg; 9628 checkTime(startTime, "getContentProviderImpl: before checkContentProviderPermission"); 9629 if ((msg = checkContentProviderPermissionLocked(cpi, r, userId, !singleton)) 9630 != null) { 9631 throw new SecurityException(msg); 9632 } 9633 checkTime(startTime, "getContentProviderImpl: after checkContentProviderPermission"); 9634 9635 if (!mProcessesReady && !mDidUpdate && !mWaitingUpdate 9636 && !cpi.processName.equals("system")) { 9637 // If this content provider does not run in the system 9638 // process, and the system is not yet ready to run other 9639 // processes, then fail fast instead of hanging. 9640 throw new IllegalArgumentException( 9641 "Attempt to launch content provider before system ready"); 9642 } 9643 9644 // Make sure that the user who owns this provider is running. If not, 9645 // we don't want to allow it to run. 9646 if (!isUserRunningLocked(userId, false)) { 9647 Slog.w(TAG, "Unable to launch app " 9648 + cpi.applicationInfo.packageName + "/" 9649 + cpi.applicationInfo.uid + " for provider " 9650 + name + ": user " + userId + " is stopped"); 9651 return null; 9652 } 9653 9654 ComponentName comp = new ComponentName(cpi.packageName, cpi.name); 9655 checkTime(startTime, "getContentProviderImpl: before getProviderByClass"); 9656 cpr = mProviderMap.getProviderByClass(comp, userId); 9657 checkTime(startTime, "getContentProviderImpl: after getProviderByClass"); 9658 final boolean firstClass = cpr == null; 9659 if (firstClass) { 9660 final long ident = Binder.clearCallingIdentity(); 9661 try { 9662 checkTime(startTime, "getContentProviderImpl: before getApplicationInfo"); 9663 ApplicationInfo ai = 9664 AppGlobals.getPackageManager(). 9665 getApplicationInfo( 9666 cpi.applicationInfo.packageName, 9667 STOCK_PM_FLAGS, userId); 9668 checkTime(startTime, "getContentProviderImpl: after getApplicationInfo"); 9669 if (ai == null) { 9670 Slog.w(TAG, "No package info for content provider " 9671 + cpi.name); 9672 return null; 9673 } 9674 ai = getAppInfoForUser(ai, userId); 9675 cpr = new ContentProviderRecord(this, cpi, ai, comp, singleton); 9676 } catch (RemoteException ex) { 9677 // pm is in same process, this will never happen. 9678 } finally { 9679 Binder.restoreCallingIdentity(ident); 9680 } 9681 } 9682 9683 checkTime(startTime, "getContentProviderImpl: now have ContentProviderRecord"); 9684 9685 if (r != null && cpr.canRunHere(r)) { 9686 // If this is a multiprocess provider, then just return its 9687 // info and allow the caller to instantiate it. Only do 9688 // this if the provider is the same user as the caller's 9689 // process, or can run as root (so can be in any process). 9690 return cpr.newHolder(null); 9691 } 9692 9693 if (DEBUG_PROVIDER) Slog.w(TAG_PROVIDER, "LAUNCHING REMOTE PROVIDER (myuid " 9694 + (r != null ? r.uid : null) + " pruid " + cpr.appInfo.uid + "): " 9695 + cpr.info.name + " callers=" + Debug.getCallers(6)); 9696 9697 // This is single process, and our app is now connecting to it. 9698 // See if we are already in the process of launching this 9699 // provider. 9700 final int N = mLaunchingProviders.size(); 9701 int i; 9702 for (i = 0; i < N; i++) { 9703 if (mLaunchingProviders.get(i) == cpr) { 9704 break; 9705 } 9706 } 9707 9708 // If the provider is not already being launched, then get it 9709 // started. 9710 if (i >= N) { 9711 final long origId = Binder.clearCallingIdentity(); 9712 9713 try { 9714 // Content provider is now in use, its package can't be stopped. 9715 try { 9716 checkTime(startTime, "getContentProviderImpl: before set stopped state"); 9717 AppGlobals.getPackageManager().setPackageStoppedState( 9718 cpr.appInfo.packageName, false, userId); 9719 checkTime(startTime, "getContentProviderImpl: after set stopped state"); 9720 } catch (RemoteException e) { 9721 } catch (IllegalArgumentException e) { 9722 Slog.w(TAG, "Failed trying to unstop package " 9723 + cpr.appInfo.packageName + ": " + e); 9724 } 9725 9726 // Use existing process if already started 9727 checkTime(startTime, "getContentProviderImpl: looking for process record"); 9728 ProcessRecord proc = getProcessRecordLocked( 9729 cpi.processName, cpr.appInfo.uid, false); 9730 if (proc != null && proc.thread != null) { 9731 if (DEBUG_PROVIDER) Slog.d(TAG_PROVIDER, 9732 "Installing in existing process " + proc); 9733 if (!proc.pubProviders.containsKey(cpi.name)) { 9734 checkTime(startTime, "getContentProviderImpl: scheduling install"); 9735 proc.pubProviders.put(cpi.name, cpr); 9736 try { 9737 proc.thread.scheduleInstallProvider(cpi); 9738 } catch (RemoteException e) { 9739 } 9740 } 9741 } else { 9742 checkTime(startTime, "getContentProviderImpl: before start process"); 9743 proc = startProcessLocked(cpi.processName, 9744 cpr.appInfo, false, 0, "content provider", 9745 new ComponentName(cpi.applicationInfo.packageName, 9746 cpi.name), false, false, false); 9747 checkTime(startTime, "getContentProviderImpl: after start process"); 9748 if (proc == null) { 9749 Slog.w(TAG, "Unable to launch app " 9750 + cpi.applicationInfo.packageName + "/" 9751 + cpi.applicationInfo.uid + " for provider " 9752 + name + ": process is bad"); 9753 return null; 9754 } 9755 } 9756 cpr.launchingApp = proc; 9757 mLaunchingProviders.add(cpr); 9758 } finally { 9759 Binder.restoreCallingIdentity(origId); 9760 } 9761 } 9762 9763 checkTime(startTime, "getContentProviderImpl: updating data structures"); 9764 9765 // Make sure the provider is published (the same provider class 9766 // may be published under multiple names). 9767 if (firstClass) { 9768 mProviderMap.putProviderByClass(comp, cpr); 9769 } 9770 9771 mProviderMap.putProviderByName(name, cpr); 9772 conn = incProviderCountLocked(r, cpr, token, stable); 9773 if (conn != null) { 9774 conn.waiting = true; 9775 } 9776 } 9777 checkTime(startTime, "getContentProviderImpl: done!"); 9778 } 9779 9780 // Wait for the provider to be published... 9781 synchronized (cpr) { 9782 while (cpr.provider == null) { 9783 if (cpr.launchingApp == null) { 9784 Slog.w(TAG, "Unable to launch app " 9785 + cpi.applicationInfo.packageName + "/" 9786 + cpi.applicationInfo.uid + " for provider " 9787 + name + ": launching app became null"); 9788 EventLog.writeEvent(EventLogTags.AM_PROVIDER_LOST_PROCESS, 9789 UserHandle.getUserId(cpi.applicationInfo.uid), 9790 cpi.applicationInfo.packageName, 9791 cpi.applicationInfo.uid, name); 9792 return null; 9793 } 9794 try { 9795 if (DEBUG_MU) Slog.v(TAG_MU, 9796 "Waiting to start provider " + cpr 9797 + " launchingApp=" + cpr.launchingApp); 9798 if (conn != null) { 9799 conn.waiting = true; 9800 } 9801 cpr.wait(); 9802 } catch (InterruptedException ex) { 9803 } finally { 9804 if (conn != null) { 9805 conn.waiting = false; 9806 } 9807 } 9808 } 9809 } 9810 return cpr != null ? cpr.newHolder(conn) : null; 9811 } 9812 9813 @Override getContentProvider( IApplicationThread caller, String name, int userId, boolean stable)9814 public final ContentProviderHolder getContentProvider( 9815 IApplicationThread caller, String name, int userId, boolean stable) { 9816 enforceNotIsolatedCaller("getContentProvider"); 9817 if (caller == null) { 9818 String msg = "null IApplicationThread when getting content provider " 9819 + name; 9820 Slog.w(TAG, msg); 9821 throw new SecurityException(msg); 9822 } 9823 // The incoming user check is now handled in checkContentProviderPermissionLocked() to deal 9824 // with cross-user grant. 9825 return getContentProviderImpl(caller, name, null, stable, userId); 9826 } 9827 getContentProviderExternal( String name, int userId, IBinder token)9828 public ContentProviderHolder getContentProviderExternal( 9829 String name, int userId, IBinder token) { 9830 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 9831 "Do not have permission in call getContentProviderExternal()"); 9832 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, 9833 false, ALLOW_FULL_ONLY, "getContentProvider", null); 9834 return getContentProviderExternalUnchecked(name, token, userId); 9835 } 9836 getContentProviderExternalUnchecked(String name, IBinder token, int userId)9837 private ContentProviderHolder getContentProviderExternalUnchecked(String name, 9838 IBinder token, int userId) { 9839 return getContentProviderImpl(null, name, token, true, userId); 9840 } 9841 9842 /** 9843 * Drop a content provider from a ProcessRecord's bookkeeping 9844 */ removeContentProvider(IBinder connection, boolean stable)9845 public void removeContentProvider(IBinder connection, boolean stable) { 9846 enforceNotIsolatedCaller("removeContentProvider"); 9847 long ident = Binder.clearCallingIdentity(); 9848 try { 9849 synchronized (this) { 9850 ContentProviderConnection conn; 9851 try { 9852 conn = (ContentProviderConnection)connection; 9853 } catch (ClassCastException e) { 9854 String msg ="removeContentProvider: " + connection 9855 + " not a ContentProviderConnection"; 9856 Slog.w(TAG, msg); 9857 throw new IllegalArgumentException(msg); 9858 } 9859 if (conn == null) { 9860 throw new NullPointerException("connection is null"); 9861 } 9862 if (decProviderCountLocked(conn, null, null, stable)) { 9863 updateOomAdjLocked(); 9864 } 9865 } 9866 } finally { 9867 Binder.restoreCallingIdentity(ident); 9868 } 9869 } 9870 removeContentProviderExternal(String name, IBinder token)9871 public void removeContentProviderExternal(String name, IBinder token) { 9872 enforceCallingPermission(android.Manifest.permission.ACCESS_CONTENT_PROVIDERS_EXTERNALLY, 9873 "Do not have permission in call removeContentProviderExternal()"); 9874 int userId = UserHandle.getCallingUserId(); 9875 long ident = Binder.clearCallingIdentity(); 9876 try { 9877 removeContentProviderExternalUnchecked(name, token, userId); 9878 } finally { 9879 Binder.restoreCallingIdentity(ident); 9880 } 9881 } 9882 removeContentProviderExternalUnchecked(String name, IBinder token, int userId)9883 private void removeContentProviderExternalUnchecked(String name, IBinder token, int userId) { 9884 synchronized (this) { 9885 ContentProviderRecord cpr = mProviderMap.getProviderByName(name, userId); 9886 if(cpr == null) { 9887 //remove from mProvidersByClass 9888 if(DEBUG_ALL) Slog.v(TAG, name+" content provider not found in providers list"); 9889 return; 9890 } 9891 9892 //update content provider record entry info 9893 ComponentName comp = new ComponentName(cpr.info.packageName, cpr.info.name); 9894 ContentProviderRecord localCpr = mProviderMap.getProviderByClass(comp, userId); 9895 if (localCpr.hasExternalProcessHandles()) { 9896 if (localCpr.removeExternalProcessHandleLocked(token)) { 9897 updateOomAdjLocked(); 9898 } else { 9899 Slog.e(TAG, "Attmpt to remove content provider " + localCpr 9900 + " with no external reference for token: " 9901 + token + "."); 9902 } 9903 } else { 9904 Slog.e(TAG, "Attmpt to remove content provider: " + localCpr 9905 + " with no external references."); 9906 } 9907 } 9908 } 9909 publishContentProviders(IApplicationThread caller, List<ContentProviderHolder> providers)9910 public final void publishContentProviders(IApplicationThread caller, 9911 List<ContentProviderHolder> providers) { 9912 if (providers == null) { 9913 return; 9914 } 9915 9916 enforceNotIsolatedCaller("publishContentProviders"); 9917 synchronized (this) { 9918 final ProcessRecord r = getRecordForAppLocked(caller); 9919 if (DEBUG_MU) Slog.v(TAG_MU, "ProcessRecord uid = " + r.uid); 9920 if (r == null) { 9921 throw new SecurityException( 9922 "Unable to find app for caller " + caller 9923 + " (pid=" + Binder.getCallingPid() 9924 + ") when publishing content providers"); 9925 } 9926 9927 final long origId = Binder.clearCallingIdentity(); 9928 9929 final int N = providers.size(); 9930 for (int i = 0; i < N; i++) { 9931 ContentProviderHolder src = providers.get(i); 9932 if (src == null || src.info == null || src.provider == null) { 9933 continue; 9934 } 9935 ContentProviderRecord dst = r.pubProviders.get(src.info.name); 9936 if (DEBUG_MU) Slog.v(TAG_MU, "ContentProviderRecord uid = " + dst.uid); 9937 if (dst != null) { 9938 ComponentName comp = new ComponentName(dst.info.packageName, dst.info.name); 9939 mProviderMap.putProviderByClass(comp, dst); 9940 String names[] = dst.info.authority.split(";"); 9941 for (int j = 0; j < names.length; j++) { 9942 mProviderMap.putProviderByName(names[j], dst); 9943 } 9944 9945 int launchingCount = mLaunchingProviders.size(); 9946 int j; 9947 boolean wasInLaunchingProviders = false; 9948 for (j = 0; j < launchingCount; j++) { 9949 if (mLaunchingProviders.get(j) == dst) { 9950 mLaunchingProviders.remove(j); 9951 wasInLaunchingProviders = true; 9952 j--; 9953 launchingCount--; 9954 } 9955 } 9956 if (wasInLaunchingProviders) { 9957 mHandler.removeMessages(CONTENT_PROVIDER_PUBLISH_TIMEOUT_MSG, r); 9958 } 9959 synchronized (dst) { 9960 dst.provider = src.provider; 9961 dst.proc = r; 9962 dst.notifyAll(); 9963 } 9964 updateOomAdjLocked(r); 9965 maybeUpdateProviderUsageStatsLocked(r, src.info.packageName, 9966 src.info.authority); 9967 } 9968 } 9969 9970 Binder.restoreCallingIdentity(origId); 9971 } 9972 } 9973 refContentProvider(IBinder connection, int stable, int unstable)9974 public boolean refContentProvider(IBinder connection, int stable, int unstable) { 9975 ContentProviderConnection conn; 9976 try { 9977 conn = (ContentProviderConnection)connection; 9978 } catch (ClassCastException e) { 9979 String msg ="refContentProvider: " + connection 9980 + " not a ContentProviderConnection"; 9981 Slog.w(TAG, msg); 9982 throw new IllegalArgumentException(msg); 9983 } 9984 if (conn == null) { 9985 throw new NullPointerException("connection is null"); 9986 } 9987 9988 synchronized (this) { 9989 if (stable > 0) { 9990 conn.numStableIncs += stable; 9991 } 9992 stable = conn.stableCount + stable; 9993 if (stable < 0) { 9994 throw new IllegalStateException("stableCount < 0: " + stable); 9995 } 9996 9997 if (unstable > 0) { 9998 conn.numUnstableIncs += unstable; 9999 } 10000 unstable = conn.unstableCount + unstable; 10001 if (unstable < 0) { 10002 throw new IllegalStateException("unstableCount < 0: " + unstable); 10003 } 10004 10005 if ((stable+unstable) <= 0) { 10006 throw new IllegalStateException("ref counts can't go to zero here: stable=" 10007 + stable + " unstable=" + unstable); 10008 } 10009 conn.stableCount = stable; 10010 conn.unstableCount = unstable; 10011 return !conn.dead; 10012 } 10013 } 10014 unstableProviderDied(IBinder connection)10015 public void unstableProviderDied(IBinder connection) { 10016 ContentProviderConnection conn; 10017 try { 10018 conn = (ContentProviderConnection)connection; 10019 } catch (ClassCastException e) { 10020 String msg ="refContentProvider: " + connection 10021 + " not a ContentProviderConnection"; 10022 Slog.w(TAG, msg); 10023 throw new IllegalArgumentException(msg); 10024 } 10025 if (conn == null) { 10026 throw new NullPointerException("connection is null"); 10027 } 10028 10029 // Safely retrieve the content provider associated with the connection. 10030 IContentProvider provider; 10031 synchronized (this) { 10032 provider = conn.provider.provider; 10033 } 10034 10035 if (provider == null) { 10036 // Um, yeah, we're way ahead of you. 10037 return; 10038 } 10039 10040 // Make sure the caller is being honest with us. 10041 if (provider.asBinder().pingBinder()) { 10042 // Er, no, still looks good to us. 10043 synchronized (this) { 10044 Slog.w(TAG, "unstableProviderDied: caller " + Binder.getCallingUid() 10045 + " says " + conn + " died, but we don't agree"); 10046 return; 10047 } 10048 } 10049 10050 // Well look at that! It's dead! 10051 synchronized (this) { 10052 if (conn.provider.provider != provider) { 10053 // But something changed... good enough. 10054 return; 10055 } 10056 10057 ProcessRecord proc = conn.provider.proc; 10058 if (proc == null || proc.thread == null) { 10059 // Seems like the process is already cleaned up. 10060 return; 10061 } 10062 10063 // As far as we're concerned, this is just like receiving a 10064 // death notification... just a bit prematurely. 10065 Slog.i(TAG, "Process " + proc.processName + " (pid " + proc.pid 10066 + ") early provider death"); 10067 final long ident = Binder.clearCallingIdentity(); 10068 try { 10069 appDiedLocked(proc); 10070 } finally { 10071 Binder.restoreCallingIdentity(ident); 10072 } 10073 } 10074 } 10075 10076 @Override appNotRespondingViaProvider(IBinder connection)10077 public void appNotRespondingViaProvider(IBinder connection) { 10078 enforceCallingPermission( 10079 android.Manifest.permission.REMOVE_TASKS, "appNotRespondingViaProvider()"); 10080 10081 final ContentProviderConnection conn = (ContentProviderConnection) connection; 10082 if (conn == null) { 10083 Slog.w(TAG, "ContentProviderConnection is null"); 10084 return; 10085 } 10086 10087 final ProcessRecord host = conn.provider.proc; 10088 if (host == null) { 10089 Slog.w(TAG, "Failed to find hosting ProcessRecord"); 10090 return; 10091 } 10092 10093 final long token = Binder.clearCallingIdentity(); 10094 try { 10095 appNotResponding(host, null, null, false, "ContentProvider not responding"); 10096 } finally { 10097 Binder.restoreCallingIdentity(token); 10098 } 10099 } 10100 installSystemProviders()10101 public final void installSystemProviders() { 10102 List<ProviderInfo> providers; 10103 synchronized (this) { 10104 ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID); 10105 providers = generateApplicationProvidersLocked(app); 10106 if (providers != null) { 10107 for (int i=providers.size()-1; i>=0; i--) { 10108 ProviderInfo pi = (ProviderInfo)providers.get(i); 10109 if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) { 10110 Slog.w(TAG, "Not installing system proc provider " + pi.name 10111 + ": not system .apk"); 10112 providers.remove(i); 10113 } 10114 } 10115 } 10116 } 10117 if (providers != null) { 10118 mSystemThread.installSystemProviders(providers); 10119 } 10120 10121 mCoreSettingsObserver = new CoreSettingsObserver(this); 10122 10123 //mUsageStatsService.monitorPackages(); 10124 } 10125 10126 /** 10127 * Allows apps to retrieve the MIME type of a URI. 10128 * If an app is in the same user as the ContentProvider, or if it is allowed to interact across 10129 * users, then it does not need permission to access the ContentProvider. 10130 * Either, it needs cross-user uri grants. 10131 * 10132 * CTS tests for this functionality can be run with "runtest cts-appsecurity". 10133 * 10134 * Test cases are at cts/tests/appsecurity-tests/test-apps/UsePermissionDiffCert/ 10135 * src/com/android/cts/usespermissiondiffcertapp/AccessPermissionWithDiffSigTest.java 10136 */ getProviderMimeType(Uri uri, int userId)10137 public String getProviderMimeType(Uri uri, int userId) { 10138 enforceNotIsolatedCaller("getProviderMimeType"); 10139 final String name = uri.getAuthority(); 10140 int callingUid = Binder.getCallingUid(); 10141 int callingPid = Binder.getCallingPid(); 10142 long ident = 0; 10143 boolean clearedIdentity = false; 10144 userId = unsafeConvertIncomingUser(userId); 10145 if (canClearIdentity(callingPid, callingUid, userId)) { 10146 clearedIdentity = true; 10147 ident = Binder.clearCallingIdentity(); 10148 } 10149 ContentProviderHolder holder = null; 10150 try { 10151 holder = getContentProviderExternalUnchecked(name, null, userId); 10152 if (holder != null) { 10153 return holder.provider.getType(uri); 10154 } 10155 } catch (RemoteException e) { 10156 Log.w(TAG, "Content provider dead retrieving " + uri, e); 10157 return null; 10158 } finally { 10159 // We need to clear the identity to call removeContentProviderExternalUnchecked 10160 if (!clearedIdentity) { 10161 ident = Binder.clearCallingIdentity(); 10162 } 10163 try { 10164 if (holder != null) { 10165 removeContentProviderExternalUnchecked(name, null, userId); 10166 } 10167 } finally { 10168 Binder.restoreCallingIdentity(ident); 10169 } 10170 } 10171 10172 return null; 10173 } 10174 canClearIdentity(int callingPid, int callingUid, int userId)10175 private boolean canClearIdentity(int callingPid, int callingUid, int userId) { 10176 if (UserHandle.getUserId(callingUid) == userId) { 10177 return true; 10178 } 10179 if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 10180 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED 10181 || checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 10182 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 10183 return true; 10184 } 10185 return false; 10186 } 10187 10188 // ========================================================= 10189 // GLOBAL MANAGEMENT 10190 // ========================================================= 10191 newProcessRecordLocked(ApplicationInfo info, String customProcess, boolean isolated, int isolatedUid)10192 final ProcessRecord newProcessRecordLocked(ApplicationInfo info, String customProcess, 10193 boolean isolated, int isolatedUid) { 10194 String proc = customProcess != null ? customProcess : info.processName; 10195 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 10196 final int userId = UserHandle.getUserId(info.uid); 10197 int uid = info.uid; 10198 if (isolated) { 10199 if (isolatedUid == 0) { 10200 int stepsLeft = Process.LAST_ISOLATED_UID - Process.FIRST_ISOLATED_UID + 1; 10201 while (true) { 10202 if (mNextIsolatedProcessUid < Process.FIRST_ISOLATED_UID 10203 || mNextIsolatedProcessUid > Process.LAST_ISOLATED_UID) { 10204 mNextIsolatedProcessUid = Process.FIRST_ISOLATED_UID; 10205 } 10206 uid = UserHandle.getUid(userId, mNextIsolatedProcessUid); 10207 mNextIsolatedProcessUid++; 10208 if (mIsolatedProcesses.indexOfKey(uid) < 0) { 10209 // No process for this uid, use it. 10210 break; 10211 } 10212 stepsLeft--; 10213 if (stepsLeft <= 0) { 10214 return null; 10215 } 10216 } 10217 } else { 10218 // Special case for startIsolatedProcess (internal only), where 10219 // the uid of the isolated process is specified by the caller. 10220 uid = isolatedUid; 10221 } 10222 } 10223 final ProcessRecord r = new ProcessRecord(stats, info, proc, uid); 10224 if (!mBooted && !mBooting 10225 && userId == UserHandle.USER_OWNER 10226 && (info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 10227 r.persistent = true; 10228 } 10229 addProcessNameLocked(r); 10230 return r; 10231 } 10232 addAppLocked(ApplicationInfo info, boolean isolated, String abiOverride)10233 final ProcessRecord addAppLocked(ApplicationInfo info, boolean isolated, 10234 String abiOverride) { 10235 ProcessRecord app; 10236 if (!isolated) { 10237 app = getProcessRecordLocked(info.processName, info.uid, true); 10238 } else { 10239 app = null; 10240 } 10241 10242 if (app == null) { 10243 app = newProcessRecordLocked(info, null, isolated, 0); 10244 updateLruProcessLocked(app, false, null); 10245 updateOomAdjLocked(); 10246 } 10247 10248 // This package really, really can not be stopped. 10249 try { 10250 AppGlobals.getPackageManager().setPackageStoppedState( 10251 info.packageName, false, UserHandle.getUserId(app.uid)); 10252 } catch (RemoteException e) { 10253 } catch (IllegalArgumentException e) { 10254 Slog.w(TAG, "Failed trying to unstop package " 10255 + info.packageName + ": " + e); 10256 } 10257 10258 if ((info.flags & PERSISTENT_MASK) == PERSISTENT_MASK) { 10259 app.persistent = true; 10260 app.maxAdj = ProcessList.PERSISTENT_PROC_ADJ; 10261 } 10262 if (app.thread == null && mPersistentStartingProcesses.indexOf(app) < 0) { 10263 mPersistentStartingProcesses.add(app); 10264 startProcessLocked(app, "added application", app.processName, abiOverride, 10265 null /* entryPoint */, null /* entryPointArgs */); 10266 } 10267 10268 return app; 10269 } 10270 unhandledBack()10271 public void unhandledBack() { 10272 enforceCallingPermission(android.Manifest.permission.FORCE_BACK, 10273 "unhandledBack()"); 10274 10275 synchronized(this) { 10276 final long origId = Binder.clearCallingIdentity(); 10277 try { 10278 getFocusedStack().unhandledBackLocked(); 10279 } finally { 10280 Binder.restoreCallingIdentity(origId); 10281 } 10282 } 10283 } 10284 openContentUri(Uri uri)10285 public ParcelFileDescriptor openContentUri(Uri uri) throws RemoteException { 10286 enforceNotIsolatedCaller("openContentUri"); 10287 final int userId = UserHandle.getCallingUserId(); 10288 String name = uri.getAuthority(); 10289 ContentProviderHolder cph = getContentProviderExternalUnchecked(name, null, userId); 10290 ParcelFileDescriptor pfd = null; 10291 if (cph != null) { 10292 // We record the binder invoker's uid in thread-local storage before 10293 // going to the content provider to open the file. Later, in the code 10294 // that handles all permissions checks, we look for this uid and use 10295 // that rather than the Activity Manager's own uid. The effect is that 10296 // we do the check against the caller's permissions even though it looks 10297 // to the content provider like the Activity Manager itself is making 10298 // the request. 10299 Binder token = new Binder(); 10300 sCallerIdentity.set(new Identity( 10301 token, Binder.getCallingPid(), Binder.getCallingUid())); 10302 try { 10303 pfd = cph.provider.openFile(null, uri, "r", null, token); 10304 } catch (FileNotFoundException e) { 10305 // do nothing; pfd will be returned null 10306 } finally { 10307 // Ensure that whatever happens, we clean up the identity state 10308 sCallerIdentity.remove(); 10309 // Ensure we're done with the provider. 10310 removeContentProviderExternalUnchecked(name, null, userId); 10311 } 10312 } else { 10313 Slog.d(TAG, "Failed to get provider for authority '" + name + "'"); 10314 } 10315 return pfd; 10316 } 10317 10318 // Actually is sleeping or shutting down or whatever else in the future 10319 // is an inactive state. isSleepingOrShuttingDown()10320 public boolean isSleepingOrShuttingDown() { 10321 return isSleeping() || mShuttingDown; 10322 } 10323 isSleeping()10324 public boolean isSleeping() { 10325 return mSleeping; 10326 } 10327 onWakefulnessChanged(int wakefulness)10328 void onWakefulnessChanged(int wakefulness) { 10329 synchronized(this) { 10330 mWakefulness = wakefulness; 10331 updateSleepIfNeededLocked(); 10332 } 10333 } 10334 finishRunningVoiceLocked()10335 void finishRunningVoiceLocked() { 10336 if (mRunningVoice != null) { 10337 mRunningVoice = null; 10338 mVoiceWakeLock.release(); 10339 updateSleepIfNeededLocked(); 10340 } 10341 } 10342 startTimeTrackingFocusedActivityLocked()10343 void startTimeTrackingFocusedActivityLocked() { 10344 if (!mSleeping && mCurAppTimeTracker != null && mFocusedActivity != null) { 10345 mCurAppTimeTracker.start(mFocusedActivity.packageName); 10346 } 10347 } 10348 updateSleepIfNeededLocked()10349 void updateSleepIfNeededLocked() { 10350 if (mSleeping && !shouldSleepLocked()) { 10351 mSleeping = false; 10352 startTimeTrackingFocusedActivityLocked(); 10353 mTopProcessState = ActivityManager.PROCESS_STATE_TOP; 10354 mStackSupervisor.comeOutOfSleepIfNeededLocked(); 10355 updateOomAdjLocked(); 10356 } else if (!mSleeping && shouldSleepLocked()) { 10357 mSleeping = true; 10358 if (mCurAppTimeTracker != null) { 10359 mCurAppTimeTracker.stop(); 10360 } 10361 mTopProcessState = ActivityManager.PROCESS_STATE_TOP_SLEEPING; 10362 mStackSupervisor.goingToSleepLocked(); 10363 updateOomAdjLocked(); 10364 10365 // Initialize the wake times of all processes. 10366 checkExcessivePowerUsageLocked(false); 10367 mHandler.removeMessages(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 10368 Message nmsg = mHandler.obtainMessage(CHECK_EXCESSIVE_WAKE_LOCKS_MSG); 10369 mHandler.sendMessageDelayed(nmsg, POWER_CHECK_DELAY); 10370 } 10371 } 10372 shouldSleepLocked()10373 private boolean shouldSleepLocked() { 10374 // Resume applications while running a voice interactor. 10375 if (mRunningVoice != null) { 10376 return false; 10377 } 10378 10379 // TODO: Transform the lock screen state into a sleep token instead. 10380 switch (mWakefulness) { 10381 case PowerManagerInternal.WAKEFULNESS_AWAKE: 10382 case PowerManagerInternal.WAKEFULNESS_DREAMING: 10383 case PowerManagerInternal.WAKEFULNESS_DOZING: 10384 // Pause applications whenever the lock screen is shown or any sleep 10385 // tokens have been acquired. 10386 return (mLockScreenShown != LOCK_SCREEN_HIDDEN || !mSleepTokens.isEmpty()); 10387 case PowerManagerInternal.WAKEFULNESS_ASLEEP: 10388 default: 10389 // If we're asleep then pause applications unconditionally. 10390 return true; 10391 } 10392 } 10393 10394 /** Pokes the task persister. */ notifyTaskPersisterLocked(TaskRecord task, boolean flush)10395 void notifyTaskPersisterLocked(TaskRecord task, boolean flush) { 10396 if (task != null && task.stack != null && task.stack.isHomeStack()) { 10397 // Never persist the home stack. 10398 return; 10399 } 10400 mTaskPersister.wakeup(task, flush); 10401 } 10402 10403 /** Notifies all listeners when the task stack has changed. */ notifyTaskStackChangedLocked()10404 void notifyTaskStackChangedLocked() { 10405 mHandler.removeMessages(NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG); 10406 Message nmsg = mHandler.obtainMessage(NOTIFY_TASK_STACK_CHANGE_LISTENERS_MSG); 10407 mHandler.sendMessageDelayed(nmsg, NOTIFY_TASK_STACK_CHANGE_LISTENERS_DELAY); 10408 } 10409 10410 @Override notifyCleartextNetwork(int uid, byte[] firstPacket)10411 public void notifyCleartextNetwork(int uid, byte[] firstPacket) { 10412 mHandler.obtainMessage(NOTIFY_CLEARTEXT_NETWORK_MSG, uid, 0, firstPacket).sendToTarget(); 10413 } 10414 10415 @Override shutdown(int timeout)10416 public boolean shutdown(int timeout) { 10417 if (checkCallingPermission(android.Manifest.permission.SHUTDOWN) 10418 != PackageManager.PERMISSION_GRANTED) { 10419 throw new SecurityException("Requires permission " 10420 + android.Manifest.permission.SHUTDOWN); 10421 } 10422 10423 boolean timedout = false; 10424 10425 synchronized(this) { 10426 mShuttingDown = true; 10427 updateEventDispatchingLocked(); 10428 timedout = mStackSupervisor.shutdownLocked(timeout); 10429 } 10430 10431 mAppOpsService.shutdown(); 10432 if (mUsageStatsService != null) { 10433 mUsageStatsService.prepareShutdown(); 10434 } 10435 mBatteryStatsService.shutdown(); 10436 synchronized (this) { 10437 mProcessStats.shutdownLocked(); 10438 notifyTaskPersisterLocked(null, true); 10439 } 10440 10441 return timedout; 10442 } 10443 activitySlept(IBinder token)10444 public final void activitySlept(IBinder token) { 10445 if (DEBUG_ALL) Slog.v(TAG, "Activity slept: token=" + token); 10446 10447 final long origId = Binder.clearCallingIdentity(); 10448 10449 synchronized (this) { 10450 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 10451 if (r != null) { 10452 mStackSupervisor.activitySleptLocked(r); 10453 } 10454 } 10455 10456 Binder.restoreCallingIdentity(origId); 10457 } 10458 lockScreenShownToString()10459 private String lockScreenShownToString() { 10460 switch (mLockScreenShown) { 10461 case LOCK_SCREEN_HIDDEN: return "LOCK_SCREEN_HIDDEN"; 10462 case LOCK_SCREEN_LEAVING: return "LOCK_SCREEN_LEAVING"; 10463 case LOCK_SCREEN_SHOWN: return "LOCK_SCREEN_SHOWN"; 10464 default: return "Unknown=" + mLockScreenShown; 10465 } 10466 } 10467 logLockScreen(String msg)10468 void logLockScreen(String msg) { 10469 if (DEBUG_LOCKSCREEN) Slog.d(TAG_LOCKSCREEN, Debug.getCallers(2) + ":" + msg 10470 + " mLockScreenShown=" + lockScreenShownToString() + " mWakefulness=" 10471 + PowerManagerInternal.wakefulnessToString(mWakefulness) 10472 + " mSleeping=" + mSleeping); 10473 } 10474 startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid)10475 void startRunningVoiceLocked(IVoiceInteractionSession session, int targetUid) { 10476 mVoiceWakeLock.setWorkSource(new WorkSource(targetUid)); 10477 if (mRunningVoice == null || mRunningVoice.asBinder() != session.asBinder()) { 10478 boolean wasRunningVoice = mRunningVoice != null; 10479 mRunningVoice = session; 10480 if (!wasRunningVoice) { 10481 mVoiceWakeLock.acquire(); 10482 updateSleepIfNeededLocked(); 10483 } 10484 } 10485 } 10486 updateEventDispatchingLocked()10487 private void updateEventDispatchingLocked() { 10488 mWindowManager.setEventDispatching(mBooted && !mShuttingDown); 10489 } 10490 setLockScreenShown(boolean shown)10491 public void setLockScreenShown(boolean shown) { 10492 if (checkCallingPermission(android.Manifest.permission.DEVICE_POWER) 10493 != PackageManager.PERMISSION_GRANTED) { 10494 throw new SecurityException("Requires permission " 10495 + android.Manifest.permission.DEVICE_POWER); 10496 } 10497 10498 synchronized(this) { 10499 long ident = Binder.clearCallingIdentity(); 10500 try { 10501 if (DEBUG_LOCKSCREEN) logLockScreen(" shown=" + shown); 10502 mLockScreenShown = shown ? LOCK_SCREEN_SHOWN : LOCK_SCREEN_HIDDEN; 10503 updateSleepIfNeededLocked(); 10504 } finally { 10505 Binder.restoreCallingIdentity(ident); 10506 } 10507 } 10508 } 10509 10510 @Override stopAppSwitches()10511 public void stopAppSwitches() { 10512 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 10513 != PackageManager.PERMISSION_GRANTED) { 10514 throw new SecurityException("Requires permission " 10515 + android.Manifest.permission.STOP_APP_SWITCHES); 10516 } 10517 10518 synchronized(this) { 10519 mAppSwitchesAllowedTime = SystemClock.uptimeMillis() 10520 + APP_SWITCH_DELAY_TIME; 10521 mDidAppSwitch = false; 10522 mHandler.removeMessages(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 10523 Message msg = mHandler.obtainMessage(DO_PENDING_ACTIVITY_LAUNCHES_MSG); 10524 mHandler.sendMessageDelayed(msg, APP_SWITCH_DELAY_TIME); 10525 } 10526 } 10527 resumeAppSwitches()10528 public void resumeAppSwitches() { 10529 if (checkCallingPermission(android.Manifest.permission.STOP_APP_SWITCHES) 10530 != PackageManager.PERMISSION_GRANTED) { 10531 throw new SecurityException("Requires permission " 10532 + android.Manifest.permission.STOP_APP_SWITCHES); 10533 } 10534 10535 synchronized(this) { 10536 // Note that we don't execute any pending app switches... we will 10537 // let those wait until either the timeout, or the next start 10538 // activity request. 10539 mAppSwitchesAllowedTime = 0; 10540 } 10541 } 10542 checkAppSwitchAllowedLocked(int sourcePid, int sourceUid, int callingPid, int callingUid, String name)10543 boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid, 10544 int callingPid, int callingUid, String name) { 10545 if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) { 10546 return true; 10547 } 10548 10549 int perm = checkComponentPermission( 10550 android.Manifest.permission.STOP_APP_SWITCHES, sourcePid, 10551 sourceUid, -1, true); 10552 if (perm == PackageManager.PERMISSION_GRANTED) { 10553 return true; 10554 } 10555 10556 // If the actual IPC caller is different from the logical source, then 10557 // also see if they are allowed to control app switches. 10558 if (callingUid != -1 && callingUid != sourceUid) { 10559 perm = checkComponentPermission( 10560 android.Manifest.permission.STOP_APP_SWITCHES, callingPid, 10561 callingUid, -1, true); 10562 if (perm == PackageManager.PERMISSION_GRANTED) { 10563 return true; 10564 } 10565 } 10566 10567 Slog.w(TAG, name + " request from " + sourceUid + " stopped"); 10568 return false; 10569 } 10570 setDebugApp(String packageName, boolean waitForDebugger, boolean persistent)10571 public void setDebugApp(String packageName, boolean waitForDebugger, 10572 boolean persistent) { 10573 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 10574 "setDebugApp()"); 10575 10576 long ident = Binder.clearCallingIdentity(); 10577 try { 10578 // Note that this is not really thread safe if there are multiple 10579 // callers into it at the same time, but that's not a situation we 10580 // care about. 10581 if (persistent) { 10582 final ContentResolver resolver = mContext.getContentResolver(); 10583 Settings.Global.putString( 10584 resolver, Settings.Global.DEBUG_APP, 10585 packageName); 10586 Settings.Global.putInt( 10587 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 10588 waitForDebugger ? 1 : 0); 10589 } 10590 10591 synchronized (this) { 10592 if (!persistent) { 10593 mOrigDebugApp = mDebugApp; 10594 mOrigWaitForDebugger = mWaitForDebugger; 10595 } 10596 mDebugApp = packageName; 10597 mWaitForDebugger = waitForDebugger; 10598 mDebugTransient = !persistent; 10599 if (packageName != null) { 10600 forceStopPackageLocked(packageName, -1, false, false, true, true, 10601 false, UserHandle.USER_ALL, "set debug app"); 10602 } 10603 } 10604 } finally { 10605 Binder.restoreCallingIdentity(ident); 10606 } 10607 } 10608 setOpenGlTraceApp(ApplicationInfo app, String processName)10609 void setOpenGlTraceApp(ApplicationInfo app, String processName) { 10610 synchronized (this) { 10611 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 10612 if (!isDebuggable) { 10613 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 10614 throw new SecurityException("Process not debuggable: " + app.packageName); 10615 } 10616 } 10617 10618 mOpenGlTraceApp = processName; 10619 } 10620 } 10621 setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo)10622 void setProfileApp(ApplicationInfo app, String processName, ProfilerInfo profilerInfo) { 10623 synchronized (this) { 10624 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 10625 if (!isDebuggable) { 10626 if ((app.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 10627 throw new SecurityException("Process not debuggable: " + app.packageName); 10628 } 10629 } 10630 mProfileApp = processName; 10631 mProfileFile = profilerInfo.profileFile; 10632 if (mProfileFd != null) { 10633 try { 10634 mProfileFd.close(); 10635 } catch (IOException e) { 10636 } 10637 mProfileFd = null; 10638 } 10639 mProfileFd = profilerInfo.profileFd; 10640 mSamplingInterval = profilerInfo.samplingInterval; 10641 mAutoStopProfiler = profilerInfo.autoStopProfiler; 10642 mProfileType = 0; 10643 } 10644 } 10645 10646 @Override setAlwaysFinish(boolean enabled)10647 public void setAlwaysFinish(boolean enabled) { 10648 enforceCallingPermission(android.Manifest.permission.SET_ALWAYS_FINISH, 10649 "setAlwaysFinish()"); 10650 10651 Settings.Global.putInt( 10652 mContext.getContentResolver(), 10653 Settings.Global.ALWAYS_FINISH_ACTIVITIES, enabled ? 1 : 0); 10654 10655 synchronized (this) { 10656 mAlwaysFinishActivities = enabled; 10657 } 10658 } 10659 10660 @Override setActivityController(IActivityController controller)10661 public void setActivityController(IActivityController controller) { 10662 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 10663 "setActivityController()"); 10664 synchronized (this) { 10665 mController = controller; 10666 Watchdog.getInstance().setActivityController(controller); 10667 } 10668 } 10669 10670 @Override setUserIsMonkey(boolean userIsMonkey)10671 public void setUserIsMonkey(boolean userIsMonkey) { 10672 synchronized (this) { 10673 synchronized (mPidsSelfLocked) { 10674 final int callingPid = Binder.getCallingPid(); 10675 ProcessRecord precessRecord = mPidsSelfLocked.get(callingPid); 10676 if (precessRecord == null) { 10677 throw new SecurityException("Unknown process: " + callingPid); 10678 } 10679 if (precessRecord.instrumentationUiAutomationConnection == null) { 10680 throw new SecurityException("Only an instrumentation process " 10681 + "with a UiAutomation can call setUserIsMonkey"); 10682 } 10683 } 10684 mUserIsMonkey = userIsMonkey; 10685 } 10686 } 10687 10688 @Override isUserAMonkey()10689 public boolean isUserAMonkey() { 10690 synchronized (this) { 10691 // If there is a controller also implies the user is a monkey. 10692 return (mUserIsMonkey || mController != null); 10693 } 10694 } 10695 requestBugReport()10696 public void requestBugReport() { 10697 enforceCallingPermission(android.Manifest.permission.DUMP, "requestBugReport"); 10698 SystemProperties.set("ctl.start", "bugreport"); 10699 } 10700 getInputDispatchingTimeoutLocked(ActivityRecord r)10701 public static long getInputDispatchingTimeoutLocked(ActivityRecord r) { 10702 return r != null ? getInputDispatchingTimeoutLocked(r.app) : KEY_DISPATCHING_TIMEOUT; 10703 } 10704 getInputDispatchingTimeoutLocked(ProcessRecord r)10705 public static long getInputDispatchingTimeoutLocked(ProcessRecord r) { 10706 if (r != null && (r.instrumentationClass != null || r.usingWrapper)) { 10707 return INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT; 10708 } 10709 return KEY_DISPATCHING_TIMEOUT; 10710 } 10711 10712 @Override inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason)10713 public long inputDispatchingTimedOut(int pid, final boolean aboveSystem, String reason) { 10714 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 10715 != PackageManager.PERMISSION_GRANTED) { 10716 throw new SecurityException("Requires permission " 10717 + android.Manifest.permission.FILTER_EVENTS); 10718 } 10719 ProcessRecord proc; 10720 long timeout; 10721 synchronized (this) { 10722 synchronized (mPidsSelfLocked) { 10723 proc = mPidsSelfLocked.get(pid); 10724 } 10725 timeout = getInputDispatchingTimeoutLocked(proc); 10726 } 10727 10728 if (!inputDispatchingTimedOut(proc, null, null, aboveSystem, reason)) { 10729 return -1; 10730 } 10731 10732 return timeout; 10733 } 10734 10735 /** 10736 * Handle input dispatching timeouts. 10737 * Returns whether input dispatching should be aborted or not. 10738 */ inputDispatchingTimedOut(final ProcessRecord proc, final ActivityRecord activity, final ActivityRecord parent, final boolean aboveSystem, String reason)10739 public boolean inputDispatchingTimedOut(final ProcessRecord proc, 10740 final ActivityRecord activity, final ActivityRecord parent, 10741 final boolean aboveSystem, String reason) { 10742 if (checkCallingPermission(android.Manifest.permission.FILTER_EVENTS) 10743 != PackageManager.PERMISSION_GRANTED) { 10744 throw new SecurityException("Requires permission " 10745 + android.Manifest.permission.FILTER_EVENTS); 10746 } 10747 10748 final String annotation; 10749 if (reason == null) { 10750 annotation = "Input dispatching timed out"; 10751 } else { 10752 annotation = "Input dispatching timed out (" + reason + ")"; 10753 } 10754 10755 if (proc != null) { 10756 synchronized (this) { 10757 if (proc.debugging) { 10758 return false; 10759 } 10760 10761 if (mDidDexOpt) { 10762 // Give more time since we were dexopting. 10763 mDidDexOpt = false; 10764 return false; 10765 } 10766 10767 if (proc.instrumentationClass != null) { 10768 Bundle info = new Bundle(); 10769 info.putString("shortMsg", "keyDispatchingTimedOut"); 10770 info.putString("longMsg", annotation); 10771 finishInstrumentationLocked(proc, Activity.RESULT_CANCELED, info); 10772 return true; 10773 } 10774 } 10775 mHandler.post(new Runnable() { 10776 @Override 10777 public void run() { 10778 appNotResponding(proc, activity, parent, aboveSystem, annotation); 10779 } 10780 }); 10781 } 10782 10783 return true; 10784 } 10785 10786 @Override getAssistContextExtras(int requestType)10787 public Bundle getAssistContextExtras(int requestType) { 10788 PendingAssistExtras pae = enqueueAssistContext(requestType, null, null, null, 10789 null, UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_TIMEOUT); 10790 if (pae == null) { 10791 return null; 10792 } 10793 synchronized (pae) { 10794 while (!pae.haveResult) { 10795 try { 10796 pae.wait(); 10797 } catch (InterruptedException e) { 10798 } 10799 } 10800 } 10801 synchronized (this) { 10802 buildAssistBundleLocked(pae, pae.result); 10803 mPendingAssistExtras.remove(pae); 10804 mUiHandler.removeCallbacks(pae); 10805 } 10806 return pae.extras; 10807 } 10808 10809 @Override isAssistDataAllowedOnCurrentActivity()10810 public boolean isAssistDataAllowedOnCurrentActivity() { 10811 int userId = mCurrentUserId; 10812 synchronized (this) { 10813 ActivityRecord activity = getFocusedStack().topActivity(); 10814 if (activity == null) { 10815 return false; 10816 } 10817 userId = activity.userId; 10818 } 10819 DevicePolicyManager dpm = (DevicePolicyManager) mContext.getSystemService( 10820 Context.DEVICE_POLICY_SERVICE); 10821 return (dpm == null) || (!dpm.getScreenCaptureDisabled(null, userId)); 10822 } 10823 10824 @Override showAssistFromActivity(IBinder token, Bundle args)10825 public boolean showAssistFromActivity(IBinder token, Bundle args) { 10826 long ident = Binder.clearCallingIdentity(); 10827 try { 10828 synchronized (this) { 10829 ActivityRecord caller = ActivityRecord.forTokenLocked(token); 10830 ActivityRecord top = getFocusedStack().topActivity(); 10831 if (top != caller) { 10832 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller 10833 + " is not current top " + top); 10834 return false; 10835 } 10836 if (!top.nowVisible) { 10837 Slog.w(TAG, "showAssistFromActivity failed: caller " + caller 10838 + " is not visible"); 10839 return false; 10840 } 10841 } 10842 AssistUtils utils = new AssistUtils(mContext); 10843 return utils.showSessionForActiveService(args, 10844 VoiceInteractionSession.SHOW_SOURCE_APPLICATION, null, token); 10845 } finally { 10846 Binder.restoreCallingIdentity(ident); 10847 } 10848 } 10849 10850 @Override requestAssistContextExtras(int requestType, IResultReceiver receiver, IBinder activityToken)10851 public boolean requestAssistContextExtras(int requestType, IResultReceiver receiver, 10852 IBinder activityToken) { 10853 return enqueueAssistContext(requestType, null, null, receiver, activityToken, 10854 UserHandle.getCallingUserId(), null, PENDING_ASSIST_EXTRAS_LONG_TIMEOUT) != null; 10855 } 10856 enqueueAssistContext(int requestType, Intent intent, String hint, IResultReceiver receiver, IBinder activityToken, int userHandle, Bundle args, long timeout)10857 private PendingAssistExtras enqueueAssistContext(int requestType, Intent intent, String hint, 10858 IResultReceiver receiver, IBinder activityToken, int userHandle, Bundle args, 10859 long timeout) { 10860 enforceCallingPermission(android.Manifest.permission.GET_TOP_ACTIVITY_INFO, 10861 "enqueueAssistContext()"); 10862 synchronized (this) { 10863 ActivityRecord activity = getFocusedStack().topActivity(); 10864 if (activity == null) { 10865 Slog.w(TAG, "getAssistContextExtras failed: no top activity"); 10866 return null; 10867 } 10868 if (activity.app == null || activity.app.thread == null) { 10869 Slog.w(TAG, "getAssistContextExtras failed: no process for " + activity); 10870 return null; 10871 } 10872 if (activityToken != null) { 10873 ActivityRecord caller = ActivityRecord.forTokenLocked(activityToken); 10874 if (activity != caller) { 10875 Slog.w(TAG, "enqueueAssistContext failed: caller " + caller 10876 + " is not current top " + activity); 10877 return null; 10878 } 10879 } 10880 PendingAssistExtras pae; 10881 Bundle extras = new Bundle(); 10882 if (args != null) { 10883 extras.putAll(args); 10884 } 10885 extras.putString(Intent.EXTRA_ASSIST_PACKAGE, activity.packageName); 10886 extras.putInt(Intent.EXTRA_ASSIST_UID, activity.app.uid); 10887 pae = new PendingAssistExtras(activity, extras, intent, hint, receiver, userHandle); 10888 try { 10889 activity.app.thread.requestAssistContextExtras(activity.appToken, pae, 10890 requestType); 10891 mPendingAssistExtras.add(pae); 10892 mUiHandler.postDelayed(pae, timeout); 10893 } catch (RemoteException e) { 10894 Slog.w(TAG, "getAssistContextExtras failed: crash calling " + activity); 10895 return null; 10896 } 10897 return pae; 10898 } 10899 } 10900 pendingAssistExtrasTimedOut(PendingAssistExtras pae)10901 void pendingAssistExtrasTimedOut(PendingAssistExtras pae) { 10902 IResultReceiver receiver; 10903 synchronized (this) { 10904 mPendingAssistExtras.remove(pae); 10905 receiver = pae.receiver; 10906 } 10907 if (receiver != null) { 10908 // Caller wants result sent back to them. 10909 try { 10910 pae.receiver.send(0, null); 10911 } catch (RemoteException e) { 10912 } 10913 } 10914 } 10915 buildAssistBundleLocked(PendingAssistExtras pae, Bundle result)10916 private void buildAssistBundleLocked(PendingAssistExtras pae, Bundle result) { 10917 if (result != null) { 10918 pae.extras.putBundle(Intent.EXTRA_ASSIST_CONTEXT, result); 10919 } 10920 if (pae.hint != null) { 10921 pae.extras.putBoolean(pae.hint, true); 10922 } 10923 } 10924 reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure, AssistContent content, Uri referrer)10925 public void reportAssistContextExtras(IBinder token, Bundle extras, AssistStructure structure, 10926 AssistContent content, Uri referrer) { 10927 PendingAssistExtras pae = (PendingAssistExtras)token; 10928 synchronized (pae) { 10929 pae.result = extras; 10930 pae.structure = structure; 10931 pae.content = content; 10932 if (referrer != null) { 10933 pae.extras.putParcelable(Intent.EXTRA_REFERRER, referrer); 10934 } 10935 pae.haveResult = true; 10936 pae.notifyAll(); 10937 if (pae.intent == null && pae.receiver == null) { 10938 // Caller is just waiting for the result. 10939 return; 10940 } 10941 } 10942 10943 // We are now ready to launch the assist activity. 10944 IResultReceiver sendReceiver = null; 10945 Bundle sendBundle = null; 10946 synchronized (this) { 10947 buildAssistBundleLocked(pae, extras); 10948 boolean exists = mPendingAssistExtras.remove(pae); 10949 mUiHandler.removeCallbacks(pae); 10950 if (!exists) { 10951 // Timed out. 10952 return; 10953 } 10954 if ((sendReceiver=pae.receiver) != null) { 10955 // Caller wants result sent back to them. 10956 sendBundle = new Bundle(); 10957 sendBundle.putBundle("data", pae.extras); 10958 sendBundle.putParcelable("structure", pae.structure); 10959 sendBundle.putParcelable("content", pae.content); 10960 } 10961 } 10962 if (sendReceiver != null) { 10963 try { 10964 sendReceiver.send(0, sendBundle); 10965 } catch (RemoteException e) { 10966 } 10967 return; 10968 } 10969 10970 long ident = Binder.clearCallingIdentity(); 10971 try { 10972 pae.intent.replaceExtras(pae.extras); 10973 pae.intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK 10974 | Intent.FLAG_ACTIVITY_SINGLE_TOP 10975 | Intent.FLAG_ACTIVITY_CLEAR_TOP); 10976 closeSystemDialogs("assist"); 10977 try { 10978 mContext.startActivityAsUser(pae.intent, new UserHandle(pae.userHandle)); 10979 } catch (ActivityNotFoundException e) { 10980 Slog.w(TAG, "No activity to handle assist action.", e); 10981 } 10982 } finally { 10983 Binder.restoreCallingIdentity(ident); 10984 } 10985 } 10986 launchAssistIntent(Intent intent, int requestType, String hint, int userHandle, Bundle args)10987 public boolean launchAssistIntent(Intent intent, int requestType, String hint, int userHandle, 10988 Bundle args) { 10989 return enqueueAssistContext(requestType, intent, hint, null, null, userHandle, args, 10990 PENDING_ASSIST_EXTRAS_TIMEOUT) != null; 10991 } 10992 registerProcessObserver(IProcessObserver observer)10993 public void registerProcessObserver(IProcessObserver observer) { 10994 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 10995 "registerProcessObserver()"); 10996 synchronized (this) { 10997 mProcessObservers.register(observer); 10998 } 10999 } 11000 11001 @Override unregisterProcessObserver(IProcessObserver observer)11002 public void unregisterProcessObserver(IProcessObserver observer) { 11003 synchronized (this) { 11004 mProcessObservers.unregister(observer); 11005 } 11006 } 11007 registerUidObserver(IUidObserver observer)11008 public void registerUidObserver(IUidObserver observer) { 11009 enforceCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER, 11010 "registerUidObserver()"); 11011 synchronized (this) { 11012 mUidObservers.register(observer); 11013 } 11014 } 11015 11016 @Override unregisterUidObserver(IUidObserver observer)11017 public void unregisterUidObserver(IUidObserver observer) { 11018 synchronized (this) { 11019 mUidObservers.unregister(observer); 11020 } 11021 } 11022 11023 @Override convertFromTranslucent(IBinder token)11024 public boolean convertFromTranslucent(IBinder token) { 11025 final long origId = Binder.clearCallingIdentity(); 11026 try { 11027 synchronized (this) { 11028 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 11029 if (r == null) { 11030 return false; 11031 } 11032 final boolean translucentChanged = r.changeWindowTranslucency(true); 11033 if (translucentChanged) { 11034 r.task.stack.releaseBackgroundResources(r); 11035 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 11036 } 11037 mWindowManager.setAppFullscreen(token, true); 11038 return translucentChanged; 11039 } 11040 } finally { 11041 Binder.restoreCallingIdentity(origId); 11042 } 11043 } 11044 11045 @Override convertToTranslucent(IBinder token, ActivityOptions options)11046 public boolean convertToTranslucent(IBinder token, ActivityOptions options) { 11047 final long origId = Binder.clearCallingIdentity(); 11048 try { 11049 synchronized (this) { 11050 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 11051 if (r == null) { 11052 return false; 11053 } 11054 int index = r.task.mActivities.lastIndexOf(r); 11055 if (index > 0) { 11056 ActivityRecord under = r.task.mActivities.get(index - 1); 11057 under.returningOptions = options; 11058 } 11059 final boolean translucentChanged = r.changeWindowTranslucency(false); 11060 if (translucentChanged) { 11061 r.task.stack.convertActivityToTranslucent(r); 11062 } 11063 mStackSupervisor.ensureActivitiesVisibleLocked(null, 0); 11064 mWindowManager.setAppFullscreen(token, false); 11065 return translucentChanged; 11066 } 11067 } finally { 11068 Binder.restoreCallingIdentity(origId); 11069 } 11070 } 11071 11072 @Override requestVisibleBehind(IBinder token, boolean visible)11073 public boolean requestVisibleBehind(IBinder token, boolean visible) { 11074 final long origId = Binder.clearCallingIdentity(); 11075 try { 11076 synchronized (this) { 11077 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 11078 if (r != null) { 11079 return mStackSupervisor.requestVisibleBehindLocked(r, visible); 11080 } 11081 } 11082 return false; 11083 } finally { 11084 Binder.restoreCallingIdentity(origId); 11085 } 11086 } 11087 11088 @Override isBackgroundVisibleBehind(IBinder token)11089 public boolean isBackgroundVisibleBehind(IBinder token) { 11090 final long origId = Binder.clearCallingIdentity(); 11091 try { 11092 synchronized (this) { 11093 final ActivityStack stack = ActivityRecord.getStackLocked(token); 11094 final boolean visible = stack == null ? false : stack.hasVisibleBehindActivity(); 11095 if (DEBUG_VISIBLE_BEHIND) Slog.d(TAG_VISIBLE_BEHIND, 11096 "isBackgroundVisibleBehind: stack=" + stack + " visible=" + visible); 11097 return visible; 11098 } 11099 } finally { 11100 Binder.restoreCallingIdentity(origId); 11101 } 11102 } 11103 11104 @Override getActivityOptions(IBinder token)11105 public ActivityOptions getActivityOptions(IBinder token) { 11106 final long origId = Binder.clearCallingIdentity(); 11107 try { 11108 synchronized (this) { 11109 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 11110 if (r != null) { 11111 final ActivityOptions activityOptions = r.pendingOptions; 11112 r.pendingOptions = null; 11113 return activityOptions; 11114 } 11115 return null; 11116 } 11117 } finally { 11118 Binder.restoreCallingIdentity(origId); 11119 } 11120 } 11121 11122 @Override setImmersive(IBinder token, boolean immersive)11123 public void setImmersive(IBinder token, boolean immersive) { 11124 synchronized(this) { 11125 final ActivityRecord r = ActivityRecord.isInStackLocked(token); 11126 if (r == null) { 11127 throw new IllegalArgumentException(); 11128 } 11129 r.immersive = immersive; 11130 11131 // update associated state if we're frontmost 11132 if (r == mFocusedActivity) { 11133 if (DEBUG_IMMERSIVE) Slog.d(TAG_IMMERSIVE, "Frontmost changed immersion: "+ r); 11134 applyUpdateLockStateLocked(r); 11135 } 11136 } 11137 } 11138 11139 @Override isImmersive(IBinder token)11140 public boolean isImmersive(IBinder token) { 11141 synchronized (this) { 11142 ActivityRecord r = ActivityRecord.isInStackLocked(token); 11143 if (r == null) { 11144 throw new IllegalArgumentException(); 11145 } 11146 return r.immersive; 11147 } 11148 } 11149 isTopActivityImmersive()11150 public boolean isTopActivityImmersive() { 11151 enforceNotIsolatedCaller("startActivity"); 11152 synchronized (this) { 11153 ActivityRecord r = getFocusedStack().topRunningActivityLocked(null); 11154 return (r != null) ? r.immersive : false; 11155 } 11156 } 11157 11158 @Override isTopOfTask(IBinder token)11159 public boolean isTopOfTask(IBinder token) { 11160 synchronized (this) { 11161 ActivityRecord r = ActivityRecord.isInStackLocked(token); 11162 if (r == null) { 11163 throw new IllegalArgumentException(); 11164 } 11165 return r.task.getTopActivity() == r; 11166 } 11167 } 11168 enterSafeMode()11169 public final void enterSafeMode() { 11170 synchronized(this) { 11171 // It only makes sense to do this before the system is ready 11172 // and started launching other packages. 11173 if (!mSystemReady) { 11174 try { 11175 AppGlobals.getPackageManager().enterSafeMode(); 11176 } catch (RemoteException e) { 11177 } 11178 } 11179 11180 mSafeMode = true; 11181 } 11182 } 11183 showSafeModeOverlay()11184 public final void showSafeModeOverlay() { 11185 View v = LayoutInflater.from(mContext).inflate( 11186 com.android.internal.R.layout.safe_mode, null); 11187 WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); 11188 lp.type = WindowManager.LayoutParams.TYPE_SECURE_SYSTEM_OVERLAY; 11189 lp.width = WindowManager.LayoutParams.WRAP_CONTENT; 11190 lp.height = WindowManager.LayoutParams.WRAP_CONTENT; 11191 lp.gravity = Gravity.BOTTOM | Gravity.START; 11192 lp.format = v.getBackground().getOpacity(); 11193 lp.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE 11194 | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; 11195 lp.privateFlags |= WindowManager.LayoutParams.PRIVATE_FLAG_SHOW_FOR_ALL_USERS; 11196 ((WindowManager)mContext.getSystemService( 11197 Context.WINDOW_SERVICE)).addView(v, lp); 11198 } 11199 noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg, String tag)11200 public void noteWakeupAlarm(IIntentSender sender, int sourceUid, String sourcePkg, String tag) { 11201 if (!(sender instanceof PendingIntentRecord)) { 11202 return; 11203 } 11204 final PendingIntentRecord rec = (PendingIntentRecord)sender; 11205 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 11206 synchronized (stats) { 11207 if (mBatteryStatsService.isOnBattery()) { 11208 mBatteryStatsService.enforceCallingPermission(); 11209 int MY_UID = Binder.getCallingUid(); 11210 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid; 11211 BatteryStatsImpl.Uid.Pkg pkg = 11212 stats.getPackageStatsLocked(sourceUid >= 0 ? sourceUid : uid, 11213 sourcePkg != null ? sourcePkg : rec.key.packageName); 11214 pkg.noteWakeupAlarmLocked(tag); 11215 } 11216 } 11217 } 11218 noteAlarmStart(IIntentSender sender, int sourceUid, String tag)11219 public void noteAlarmStart(IIntentSender sender, int sourceUid, String tag) { 11220 if (!(sender instanceof PendingIntentRecord)) { 11221 return; 11222 } 11223 final PendingIntentRecord rec = (PendingIntentRecord)sender; 11224 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 11225 synchronized (stats) { 11226 mBatteryStatsService.enforceCallingPermission(); 11227 int MY_UID = Binder.getCallingUid(); 11228 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid; 11229 mBatteryStatsService.noteAlarmStart(tag, sourceUid >= 0 ? sourceUid : uid); 11230 } 11231 } 11232 noteAlarmFinish(IIntentSender sender, int sourceUid, String tag)11233 public void noteAlarmFinish(IIntentSender sender, int sourceUid, String tag) { 11234 if (!(sender instanceof PendingIntentRecord)) { 11235 return; 11236 } 11237 final PendingIntentRecord rec = (PendingIntentRecord)sender; 11238 final BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 11239 synchronized (stats) { 11240 mBatteryStatsService.enforceCallingPermission(); 11241 int MY_UID = Binder.getCallingUid(); 11242 int uid = rec.uid == MY_UID ? Process.SYSTEM_UID : rec.uid; 11243 mBatteryStatsService.noteAlarmFinish(tag, sourceUid >= 0 ? sourceUid : uid); 11244 } 11245 } 11246 killPids(int[] pids, String pReason, boolean secure)11247 public boolean killPids(int[] pids, String pReason, boolean secure) { 11248 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 11249 throw new SecurityException("killPids only available to the system"); 11250 } 11251 String reason = (pReason == null) ? "Unknown" : pReason; 11252 // XXX Note: don't acquire main activity lock here, because the window 11253 // manager calls in with its locks held. 11254 11255 boolean killed = false; 11256 synchronized (mPidsSelfLocked) { 11257 int[] types = new int[pids.length]; 11258 int worstType = 0; 11259 for (int i=0; i<pids.length; i++) { 11260 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 11261 if (proc != null) { 11262 int type = proc.setAdj; 11263 types[i] = type; 11264 if (type > worstType) { 11265 worstType = type; 11266 } 11267 } 11268 } 11269 11270 // If the worst oom_adj is somewhere in the cached proc LRU range, 11271 // then constrain it so we will kill all cached procs. 11272 if (worstType < ProcessList.CACHED_APP_MAX_ADJ 11273 && worstType > ProcessList.CACHED_APP_MIN_ADJ) { 11274 worstType = ProcessList.CACHED_APP_MIN_ADJ; 11275 } 11276 11277 // If this is not a secure call, don't let it kill processes that 11278 // are important. 11279 if (!secure && worstType < ProcessList.SERVICE_ADJ) { 11280 worstType = ProcessList.SERVICE_ADJ; 11281 } 11282 11283 Slog.w(TAG, "Killing processes " + reason + " at adjustment " + worstType); 11284 for (int i=0; i<pids.length; i++) { 11285 ProcessRecord proc = mPidsSelfLocked.get(pids[i]); 11286 if (proc == null) { 11287 continue; 11288 } 11289 int adj = proc.setAdj; 11290 if (adj >= worstType && !proc.killedByAm) { 11291 proc.kill(reason, true); 11292 killed = true; 11293 } 11294 } 11295 } 11296 return killed; 11297 } 11298 11299 @Override killUid(int appId, int userId, String reason)11300 public void killUid(int appId, int userId, String reason) { 11301 enforceCallingPermission(Manifest.permission.KILL_UID, "killUid"); 11302 synchronized (this) { 11303 final long identity = Binder.clearCallingIdentity(); 11304 try { 11305 killPackageProcessesLocked(null, appId, userId, 11306 ProcessList.PERSISTENT_PROC_ADJ, false, true, true, true, 11307 reason != null ? reason : "kill uid"); 11308 } finally { 11309 Binder.restoreCallingIdentity(identity); 11310 } 11311 } 11312 } 11313 11314 @Override killProcessesBelowForeground(String reason)11315 public boolean killProcessesBelowForeground(String reason) { 11316 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 11317 throw new SecurityException("killProcessesBelowForeground() only available to system"); 11318 } 11319 11320 return killProcessesBelowAdj(ProcessList.FOREGROUND_APP_ADJ, reason); 11321 } 11322 killProcessesBelowAdj(int belowAdj, String reason)11323 private boolean killProcessesBelowAdj(int belowAdj, String reason) { 11324 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 11325 throw new SecurityException("killProcessesBelowAdj() only available to system"); 11326 } 11327 11328 boolean killed = false; 11329 synchronized (mPidsSelfLocked) { 11330 final int size = mPidsSelfLocked.size(); 11331 for (int i = 0; i < size; i++) { 11332 final int pid = mPidsSelfLocked.keyAt(i); 11333 final ProcessRecord proc = mPidsSelfLocked.valueAt(i); 11334 if (proc == null) continue; 11335 11336 final int adj = proc.setAdj; 11337 if (adj > belowAdj && !proc.killedByAm) { 11338 proc.kill(reason, true); 11339 killed = true; 11340 } 11341 } 11342 } 11343 return killed; 11344 } 11345 11346 @Override hang(final IBinder who, boolean allowRestart)11347 public void hang(final IBinder who, boolean allowRestart) { 11348 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 11349 != PackageManager.PERMISSION_GRANTED) { 11350 throw new SecurityException("Requires permission " 11351 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 11352 } 11353 11354 final IBinder.DeathRecipient death = new DeathRecipient() { 11355 @Override 11356 public void binderDied() { 11357 synchronized (this) { 11358 notifyAll(); 11359 } 11360 } 11361 }; 11362 11363 try { 11364 who.linkToDeath(death, 0); 11365 } catch (RemoteException e) { 11366 Slog.w(TAG, "hang: given caller IBinder is already dead."); 11367 return; 11368 } 11369 11370 synchronized (this) { 11371 Watchdog.getInstance().setAllowRestart(allowRestart); 11372 Slog.i(TAG, "Hanging system process at request of pid " + Binder.getCallingPid()); 11373 synchronized (death) { 11374 while (who.isBinderAlive()) { 11375 try { 11376 death.wait(); 11377 } catch (InterruptedException e) { 11378 } 11379 } 11380 } 11381 Watchdog.getInstance().setAllowRestart(true); 11382 } 11383 } 11384 11385 @Override restart()11386 public void restart() { 11387 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 11388 != PackageManager.PERMISSION_GRANTED) { 11389 throw new SecurityException("Requires permission " 11390 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 11391 } 11392 11393 Log.i(TAG, "Sending shutdown broadcast..."); 11394 11395 BroadcastReceiver br = new BroadcastReceiver() { 11396 @Override public void onReceive(Context context, Intent intent) { 11397 // Now the broadcast is done, finish up the low-level shutdown. 11398 Log.i(TAG, "Shutting down activity manager..."); 11399 shutdown(10000); 11400 Log.i(TAG, "Shutdown complete, restarting!"); 11401 Process.killProcess(Process.myPid()); 11402 System.exit(10); 11403 } 11404 }; 11405 11406 // First send the high-level shut down broadcast. 11407 Intent intent = new Intent(Intent.ACTION_SHUTDOWN); 11408 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 11409 intent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 11410 /* For now we are not doing a clean shutdown, because things seem to get unhappy. 11411 mContext.sendOrderedBroadcastAsUser(intent, 11412 UserHandle.ALL, null, br, mHandler, 0, null, null); 11413 */ 11414 br.onReceive(mContext, intent); 11415 } 11416 getLowRamTimeSinceIdle(long now)11417 private long getLowRamTimeSinceIdle(long now) { 11418 return mLowRamTimeSinceLastIdle + (mLowRamStartTime > 0 ? (now-mLowRamStartTime) : 0); 11419 } 11420 11421 @Override performIdleMaintenance()11422 public void performIdleMaintenance() { 11423 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 11424 != PackageManager.PERMISSION_GRANTED) { 11425 throw new SecurityException("Requires permission " 11426 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 11427 } 11428 11429 synchronized (this) { 11430 final long now = SystemClock.uptimeMillis(); 11431 final long timeSinceLastIdle = now - mLastIdleTime; 11432 final long lowRamSinceLastIdle = getLowRamTimeSinceIdle(now); 11433 mLastIdleTime = now; 11434 mLowRamTimeSinceLastIdle = 0; 11435 if (mLowRamStartTime != 0) { 11436 mLowRamStartTime = now; 11437 } 11438 11439 StringBuilder sb = new StringBuilder(128); 11440 sb.append("Idle maintenance over "); 11441 TimeUtils.formatDuration(timeSinceLastIdle, sb); 11442 sb.append(" low RAM for "); 11443 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 11444 Slog.i(TAG, sb.toString()); 11445 11446 // If at least 1/3 of our time since the last idle period has been spent 11447 // with RAM low, then we want to kill processes. 11448 boolean doKilling = lowRamSinceLastIdle > (timeSinceLastIdle/3); 11449 11450 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 11451 ProcessRecord proc = mLruProcesses.get(i); 11452 if (proc.notCachedSinceIdle) { 11453 if (proc.setProcState != ActivityManager.PROCESS_STATE_TOP_SLEEPING 11454 && proc.setProcState >= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE 11455 && proc.setProcState <= ActivityManager.PROCESS_STATE_SERVICE) { 11456 if (doKilling && proc.initialIdlePss != 0 11457 && proc.lastPss > ((proc.initialIdlePss*3)/2)) { 11458 sb = new StringBuilder(128); 11459 sb.append("Kill"); 11460 sb.append(proc.processName); 11461 sb.append(" in idle maint: pss="); 11462 sb.append(proc.lastPss); 11463 sb.append(", initialPss="); 11464 sb.append(proc.initialIdlePss); 11465 sb.append(", period="); 11466 TimeUtils.formatDuration(timeSinceLastIdle, sb); 11467 sb.append(", lowRamPeriod="); 11468 TimeUtils.formatDuration(lowRamSinceLastIdle, sb); 11469 Slog.wtfQuiet(TAG, sb.toString()); 11470 proc.kill("idle maint (pss " + proc.lastPss 11471 + " from " + proc.initialIdlePss + ")", true); 11472 } 11473 } 11474 } else if (proc.setProcState < ActivityManager.PROCESS_STATE_HOME) { 11475 proc.notCachedSinceIdle = true; 11476 proc.initialIdlePss = 0; 11477 proc.nextPssTime = ProcessList.computeNextPssTime(proc.curProcState, true, 11478 mTestPssMode, isSleeping(), now); 11479 } 11480 } 11481 11482 mHandler.removeMessages(REQUEST_ALL_PSS_MSG); 11483 mHandler.sendEmptyMessageDelayed(REQUEST_ALL_PSS_MSG, 2*60*1000); 11484 } 11485 } 11486 retrieveSettings()11487 private void retrieveSettings() { 11488 final ContentResolver resolver = mContext.getContentResolver(); 11489 String debugApp = Settings.Global.getString( 11490 resolver, Settings.Global.DEBUG_APP); 11491 boolean waitForDebugger = Settings.Global.getInt( 11492 resolver, Settings.Global.WAIT_FOR_DEBUGGER, 0) != 0; 11493 boolean alwaysFinishActivities = Settings.Global.getInt( 11494 resolver, Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0) != 0; 11495 boolean forceRtl = Settings.Global.getInt( 11496 resolver, Settings.Global.DEVELOPMENT_FORCE_RTL, 0) != 0; 11497 // Transfer any global setting for forcing RTL layout, into a System Property 11498 SystemProperties.set(Settings.Global.DEVELOPMENT_FORCE_RTL, forceRtl ? "1":"0"); 11499 11500 Configuration configuration = new Configuration(); 11501 Settings.System.getConfiguration(resolver, configuration); 11502 if (forceRtl) { 11503 // This will take care of setting the correct layout direction flags 11504 configuration.setLayoutDirection(configuration.locale); 11505 } 11506 11507 synchronized (this) { 11508 mDebugApp = mOrigDebugApp = debugApp; 11509 mWaitForDebugger = mOrigWaitForDebugger = waitForDebugger; 11510 mAlwaysFinishActivities = alwaysFinishActivities; 11511 // This happens before any activities are started, so we can 11512 // change mConfiguration in-place. 11513 updateConfigurationLocked(configuration, null, false, true); 11514 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, 11515 "Initial config: " + mConfiguration); 11516 } 11517 } 11518 11519 /** Loads resources after the current configuration has been set. */ loadResourcesOnSystemReady()11520 private void loadResourcesOnSystemReady() { 11521 final Resources res = mContext.getResources(); 11522 mHasRecents = res.getBoolean(com.android.internal.R.bool.config_hasRecents); 11523 mThumbnailWidth = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width); 11524 mThumbnailHeight = res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height); 11525 } 11526 testIsSystemReady()11527 public boolean testIsSystemReady() { 11528 // no need to synchronize(this) just to read & return the value 11529 return mSystemReady; 11530 } 11531 getCalledPreBootReceiversFile()11532 private static File getCalledPreBootReceiversFile() { 11533 File dataDir = Environment.getDataDirectory(); 11534 File systemDir = new File(dataDir, "system"); 11535 File fname = new File(systemDir, CALLED_PRE_BOOTS_FILENAME); 11536 return fname; 11537 } 11538 readLastDonePreBootReceivers()11539 private static ArrayList<ComponentName> readLastDonePreBootReceivers() { 11540 ArrayList<ComponentName> lastDoneReceivers = new ArrayList<ComponentName>(); 11541 File file = getCalledPreBootReceiversFile(); 11542 FileInputStream fis = null; 11543 try { 11544 fis = new FileInputStream(file); 11545 DataInputStream dis = new DataInputStream(new BufferedInputStream(fis, 2048)); 11546 int fvers = dis.readInt(); 11547 if (fvers == LAST_PREBOOT_DELIVERED_FILE_VERSION) { 11548 String vers = dis.readUTF(); 11549 String codename = dis.readUTF(); 11550 String build = dis.readUTF(); 11551 if (android.os.Build.VERSION.RELEASE.equals(vers) 11552 && android.os.Build.VERSION.CODENAME.equals(codename) 11553 && android.os.Build.VERSION.INCREMENTAL.equals(build)) { 11554 int num = dis.readInt(); 11555 while (num > 0) { 11556 num--; 11557 String pkg = dis.readUTF(); 11558 String cls = dis.readUTF(); 11559 lastDoneReceivers.add(new ComponentName(pkg, cls)); 11560 } 11561 } 11562 } 11563 } catch (FileNotFoundException e) { 11564 } catch (IOException e) { 11565 Slog.w(TAG, "Failure reading last done pre-boot receivers", e); 11566 } finally { 11567 if (fis != null) { 11568 try { 11569 fis.close(); 11570 } catch (IOException e) { 11571 } 11572 } 11573 } 11574 return lastDoneReceivers; 11575 } 11576 writeLastDonePreBootReceivers(ArrayList<ComponentName> list)11577 private static void writeLastDonePreBootReceivers(ArrayList<ComponentName> list) { 11578 File file = getCalledPreBootReceiversFile(); 11579 FileOutputStream fos = null; 11580 DataOutputStream dos = null; 11581 try { 11582 fos = new FileOutputStream(file); 11583 dos = new DataOutputStream(new BufferedOutputStream(fos, 2048)); 11584 dos.writeInt(LAST_PREBOOT_DELIVERED_FILE_VERSION); 11585 dos.writeUTF(android.os.Build.VERSION.RELEASE); 11586 dos.writeUTF(android.os.Build.VERSION.CODENAME); 11587 dos.writeUTF(android.os.Build.VERSION.INCREMENTAL); 11588 dos.writeInt(list.size()); 11589 for (int i=0; i<list.size(); i++) { 11590 dos.writeUTF(list.get(i).getPackageName()); 11591 dos.writeUTF(list.get(i).getClassName()); 11592 } 11593 } catch (IOException e) { 11594 Slog.w(TAG, "Failure writing last done pre-boot receivers", e); 11595 file.delete(); 11596 } finally { 11597 FileUtils.sync(fos); 11598 if (dos != null) { 11599 try { 11600 dos.close(); 11601 } catch (IOException e) { 11602 // TODO Auto-generated catch block 11603 e.printStackTrace(); 11604 } 11605 } 11606 } 11607 } 11608 11609 final class PreBootContinuation extends IIntentReceiver.Stub { 11610 final Intent intent; 11611 final Runnable onFinishCallback; 11612 final ArrayList<ComponentName> doneReceivers; 11613 final List<ResolveInfo> ris; 11614 final int[] users; 11615 int lastRi = -1; 11616 int curRi = 0; 11617 int curUser = 0; 11618 PreBootContinuation(Intent _intent, Runnable _onFinishCallback, ArrayList<ComponentName> _doneReceivers, List<ResolveInfo> _ris, int[] _users)11619 PreBootContinuation(Intent _intent, Runnable _onFinishCallback, 11620 ArrayList<ComponentName> _doneReceivers, List<ResolveInfo> _ris, int[] _users) { 11621 intent = _intent; 11622 onFinishCallback = _onFinishCallback; 11623 doneReceivers = _doneReceivers; 11624 ris = _ris; 11625 users = _users; 11626 } 11627 go()11628 void go() { 11629 if (lastRi != curRi) { 11630 ActivityInfo ai = ris.get(curRi).activityInfo; 11631 ComponentName comp = new ComponentName(ai.packageName, ai.name); 11632 intent.setComponent(comp); 11633 doneReceivers.add(comp); 11634 lastRi = curRi; 11635 CharSequence label = ai.loadLabel(mContext.getPackageManager()); 11636 showBootMessage(mContext.getString(R.string.android_preparing_apk, label), false); 11637 } 11638 Slog.i(TAG, "Pre-boot of " + intent.getComponent().toShortString() 11639 + " for user " + users[curUser]); 11640 EventLogTags.writeAmPreBoot(users[curUser], intent.getComponent().getPackageName()); 11641 broadcastIntentLocked(null, null, intent, null, this, 11642 0, null, null, null, AppOpsManager.OP_NONE, 11643 null, true, false, MY_PID, Process.SYSTEM_UID, users[curUser]); 11644 } 11645 performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky, int sendingUser)11646 public void performReceive(Intent intent, int resultCode, 11647 String data, Bundle extras, boolean ordered, 11648 boolean sticky, int sendingUser) { 11649 curUser++; 11650 if (curUser >= users.length) { 11651 curUser = 0; 11652 curRi++; 11653 if (curRi >= ris.size()) { 11654 // All done sending broadcasts! 11655 if (onFinishCallback != null) { 11656 // The raw IIntentReceiver interface is called 11657 // with the AM lock held, so redispatch to 11658 // execute our code without the lock. 11659 mHandler.post(onFinishCallback); 11660 } 11661 return; 11662 } 11663 } 11664 go(); 11665 } 11666 } 11667 deliverPreBootCompleted(final Runnable onFinishCallback, ArrayList<ComponentName> doneReceivers, int userId)11668 private boolean deliverPreBootCompleted(final Runnable onFinishCallback, 11669 ArrayList<ComponentName> doneReceivers, int userId) { 11670 Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); 11671 List<ResolveInfo> ris = null; 11672 try { 11673 ris = AppGlobals.getPackageManager().queryIntentReceivers( 11674 intent, null, 0, userId); 11675 } catch (RemoteException e) { 11676 } 11677 if (ris == null) { 11678 return false; 11679 } 11680 for (int i=ris.size()-1; i>=0; i--) { 11681 if ((ris.get(i).activityInfo.applicationInfo.flags 11682 &ApplicationInfo.FLAG_SYSTEM) == 0) { 11683 ris.remove(i); 11684 } 11685 } 11686 intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE); 11687 11688 // For User 0, load the version number. When delivering to a new user, deliver 11689 // to all receivers. 11690 if (userId == UserHandle.USER_OWNER) { 11691 ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers(); 11692 for (int i=0; i<ris.size(); i++) { 11693 ActivityInfo ai = ris.get(i).activityInfo; 11694 ComponentName comp = new ComponentName(ai.packageName, ai.name); 11695 if (lastDoneReceivers.contains(comp)) { 11696 // We already did the pre boot receiver for this app with the current 11697 // platform version, so don't do it again... 11698 ris.remove(i); 11699 i--; 11700 // ...however, do keep it as one that has been done, so we don't 11701 // forget about it when rewriting the file of last done receivers. 11702 doneReceivers.add(comp); 11703 } 11704 } 11705 } 11706 11707 if (ris.size() <= 0) { 11708 return false; 11709 } 11710 11711 // If primary user, send broadcast to all available users, else just to userId 11712 final int[] users = userId == UserHandle.USER_OWNER ? getUsersLocked() 11713 : new int[] { userId }; 11714 if (users.length <= 0) { 11715 return false; 11716 } 11717 11718 PreBootContinuation cont = new PreBootContinuation(intent, onFinishCallback, doneReceivers, 11719 ris, users); 11720 cont.go(); 11721 return true; 11722 } 11723 systemReady(final Runnable goingCallback)11724 public void systemReady(final Runnable goingCallback) { 11725 synchronized(this) { 11726 if (mSystemReady) { 11727 // If we're done calling all the receivers, run the next "boot phase" passed in 11728 // by the SystemServer 11729 if (goingCallback != null) { 11730 goingCallback.run(); 11731 } 11732 return; 11733 } 11734 11735 mLocalDeviceIdleController 11736 = LocalServices.getService(DeviceIdleController.LocalService.class); 11737 11738 // Make sure we have the current profile info, since it is needed for 11739 // security checks. 11740 updateCurrentProfileIdsLocked(); 11741 11742 mRecentTasks.clear(); 11743 mRecentTasks.addAll(mTaskPersister.restoreTasksLocked()); 11744 mRecentTasks.cleanupLocked(UserHandle.USER_ALL); 11745 mTaskPersister.startPersisting(); 11746 11747 // Check to see if there are any update receivers to run. 11748 if (!mDidUpdate) { 11749 if (mWaitingUpdate) { 11750 return; 11751 } 11752 final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>(); 11753 mWaitingUpdate = deliverPreBootCompleted(new Runnable() { 11754 public void run() { 11755 synchronized (ActivityManagerService.this) { 11756 mDidUpdate = true; 11757 } 11758 showBootMessage(mContext.getText( 11759 R.string.android_upgrading_complete), 11760 false); 11761 writeLastDonePreBootReceivers(doneReceivers); 11762 systemReady(goingCallback); 11763 } 11764 }, doneReceivers, UserHandle.USER_OWNER); 11765 11766 if (mWaitingUpdate) { 11767 return; 11768 } 11769 mDidUpdate = true; 11770 } 11771 11772 mAppOpsService.systemReady(); 11773 mSystemReady = true; 11774 } 11775 11776 ArrayList<ProcessRecord> procsToKill = null; 11777 synchronized(mPidsSelfLocked) { 11778 for (int i=mPidsSelfLocked.size()-1; i>=0; i--) { 11779 ProcessRecord proc = mPidsSelfLocked.valueAt(i); 11780 if (!isAllowedWhileBooting(proc.info)){ 11781 if (procsToKill == null) { 11782 procsToKill = new ArrayList<ProcessRecord>(); 11783 } 11784 procsToKill.add(proc); 11785 } 11786 } 11787 } 11788 11789 synchronized(this) { 11790 if (procsToKill != null) { 11791 for (int i=procsToKill.size()-1; i>=0; i--) { 11792 ProcessRecord proc = procsToKill.get(i); 11793 Slog.i(TAG, "Removing system update proc: " + proc); 11794 removeProcessLocked(proc, true, false, "system update done"); 11795 } 11796 } 11797 11798 // Now that we have cleaned up any update processes, we 11799 // are ready to start launching real processes and know that 11800 // we won't trample on them any more. 11801 mProcessesReady = true; 11802 } 11803 11804 Slog.i(TAG, "System now ready"); 11805 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, 11806 SystemClock.uptimeMillis()); 11807 11808 synchronized(this) { 11809 // Make sure we have no pre-ready processes sitting around. 11810 11811 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) { 11812 ResolveInfo ri = mContext.getPackageManager() 11813 .resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST), 11814 STOCK_PM_FLAGS); 11815 CharSequence errorMsg = null; 11816 if (ri != null) { 11817 ActivityInfo ai = ri.activityInfo; 11818 ApplicationInfo app = ai.applicationInfo; 11819 if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11820 mTopAction = Intent.ACTION_FACTORY_TEST; 11821 mTopData = null; 11822 mTopComponent = new ComponentName(app.packageName, 11823 ai.name); 11824 } else { 11825 errorMsg = mContext.getResources().getText( 11826 com.android.internal.R.string.factorytest_not_system); 11827 } 11828 } else { 11829 errorMsg = mContext.getResources().getText( 11830 com.android.internal.R.string.factorytest_no_action); 11831 } 11832 if (errorMsg != null) { 11833 mTopAction = null; 11834 mTopData = null; 11835 mTopComponent = null; 11836 Message msg = Message.obtain(); 11837 msg.what = SHOW_FACTORY_ERROR_MSG; 11838 msg.getData().putCharSequence("msg", errorMsg); 11839 mUiHandler.sendMessage(msg); 11840 } 11841 } 11842 } 11843 11844 retrieveSettings(); 11845 loadResourcesOnSystemReady(); 11846 11847 synchronized (this) { 11848 readGrantedUriPermissionsLocked(); 11849 } 11850 11851 if (goingCallback != null) goingCallback.run(); 11852 11853 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START, 11854 Integer.toString(mCurrentUserId), mCurrentUserId); 11855 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START, 11856 Integer.toString(mCurrentUserId), mCurrentUserId); 11857 mSystemServiceManager.startUser(mCurrentUserId); 11858 11859 synchronized (this) { 11860 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) { 11861 try { 11862 List apps = AppGlobals.getPackageManager(). 11863 getPersistentApplications(STOCK_PM_FLAGS); 11864 if (apps != null) { 11865 int N = apps.size(); 11866 int i; 11867 for (i=0; i<N; i++) { 11868 ApplicationInfo info 11869 = (ApplicationInfo)apps.get(i); 11870 if (info != null && 11871 !info.packageName.equals("android")) { 11872 addAppLocked(info, false, null /* ABI override */); 11873 } 11874 } 11875 } 11876 } catch (RemoteException ex) { 11877 // pm is in same process, this will never happen. 11878 } 11879 } 11880 11881 // Start up initial activity. 11882 mBooting = true; 11883 startHomeActivityLocked(mCurrentUserId, "systemReady"); 11884 11885 try { 11886 if (AppGlobals.getPackageManager().hasSystemUidErrors()) { 11887 Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your" 11888 + " data partition or your device will be unstable."); 11889 mUiHandler.obtainMessage(SHOW_UID_ERROR_MSG).sendToTarget(); 11890 } 11891 } catch (RemoteException e) { 11892 } 11893 11894 if (!Build.isBuildConsistent()) { 11895 Slog.e(TAG, "Build fingerprint is not consistent, warning user"); 11896 mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_MSG).sendToTarget(); 11897 } 11898 11899 long ident = Binder.clearCallingIdentity(); 11900 try { 11901 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 11902 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 11903 | Intent.FLAG_RECEIVER_FOREGROUND); 11904 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId); 11905 broadcastIntentLocked(null, null, intent, 11906 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 11907 null, false, false, MY_PID, Process.SYSTEM_UID, mCurrentUserId); 11908 intent = new Intent(Intent.ACTION_USER_STARTING); 11909 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 11910 intent.putExtra(Intent.EXTRA_USER_HANDLE, mCurrentUserId); 11911 broadcastIntentLocked(null, null, intent, 11912 null, new IIntentReceiver.Stub() { 11913 @Override 11914 public void performReceive(Intent intent, int resultCode, String data, 11915 Bundle extras, boolean ordered, boolean sticky, int sendingUser) 11916 throws RemoteException { 11917 } 11918 }, 0, null, null, 11919 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, 11920 null, true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 11921 } catch (Throwable t) { 11922 Slog.wtf(TAG, "Failed sending first user broadcasts", t); 11923 } finally { 11924 Binder.restoreCallingIdentity(ident); 11925 } 11926 mStackSupervisor.resumeTopActivitiesLocked(); 11927 sendUserSwitchBroadcastsLocked(-1, mCurrentUserId); 11928 } 11929 } 11930 makeAppCrashingLocked(ProcessRecord app, String shortMsg, String longMsg, String stackTrace)11931 private boolean makeAppCrashingLocked(ProcessRecord app, 11932 String shortMsg, String longMsg, String stackTrace) { 11933 app.crashing = true; 11934 app.crashingReport = generateProcessError(app, 11935 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace); 11936 startAppProblemLocked(app); 11937 app.stopFreezingAllLocked(); 11938 return handleAppCrashLocked(app, "force-crash" /*reason*/, shortMsg, longMsg, stackTrace); 11939 } 11940 makeAppNotRespondingLocked(ProcessRecord app, String activity, String shortMsg, String longMsg)11941 private void makeAppNotRespondingLocked(ProcessRecord app, 11942 String activity, String shortMsg, String longMsg) { 11943 app.notResponding = true; 11944 app.notRespondingReport = generateProcessError(app, 11945 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING, 11946 activity, shortMsg, longMsg, null); 11947 startAppProblemLocked(app); 11948 app.stopFreezingAllLocked(); 11949 } 11950 11951 /** 11952 * Generate a process error record, suitable for attachment to a ProcessRecord. 11953 * 11954 * @param app The ProcessRecord in which the error occurred. 11955 * @param condition Crashing, Application Not Responding, etc. Values are defined in 11956 * ActivityManager.AppErrorStateInfo 11957 * @param activity The activity associated with the crash, if known. 11958 * @param shortMsg Short message describing the crash. 11959 * @param longMsg Long message describing the crash. 11960 * @param stackTrace Full crash stack trace, may be null. 11961 * 11962 * @return Returns a fully-formed AppErrorStateInfo record. 11963 */ generateProcessError(ProcessRecord app, int condition, String activity, String shortMsg, String longMsg, String stackTrace)11964 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app, 11965 int condition, String activity, String shortMsg, String longMsg, String stackTrace) { 11966 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo(); 11967 11968 report.condition = condition; 11969 report.processName = app.processName; 11970 report.pid = app.pid; 11971 report.uid = app.info.uid; 11972 report.tag = activity; 11973 report.shortMsg = shortMsg; 11974 report.longMsg = longMsg; 11975 report.stackTrace = stackTrace; 11976 11977 return report; 11978 } 11979 killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog)11980 void killAppAtUsersRequest(ProcessRecord app, Dialog fromDialog) { 11981 synchronized (this) { 11982 app.crashing = false; 11983 app.crashingReport = null; 11984 app.notResponding = false; 11985 app.notRespondingReport = null; 11986 if (app.anrDialog == fromDialog) { 11987 app.anrDialog = null; 11988 } 11989 if (app.waitDialog == fromDialog) { 11990 app.waitDialog = null; 11991 } 11992 if (app.pid > 0 && app.pid != MY_PID) { 11993 handleAppCrashLocked(app, "user-terminated" /*reason*/, 11994 null /*shortMsg*/, null /*longMsg*/, null /*stackTrace*/); 11995 app.kill("user request after error", true); 11996 } 11997 } 11998 } 11999 handleAppCrashLocked(ProcessRecord app, String reason, String shortMsg, String longMsg, String stackTrace)12000 private boolean handleAppCrashLocked(ProcessRecord app, String reason, 12001 String shortMsg, String longMsg, String stackTrace) { 12002 long now = SystemClock.uptimeMillis(); 12003 12004 Long crashTime; 12005 if (!app.isolated) { 12006 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid); 12007 } else { 12008 crashTime = null; 12009 } 12010 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) { 12011 // This process loses! 12012 Slog.w(TAG, "Process " + app.info.processName 12013 + " has crashed too many times: killing!"); 12014 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH, 12015 app.userId, app.info.processName, app.uid); 12016 mStackSupervisor.handleAppCrashLocked(app); 12017 if (!app.persistent) { 12018 // We don't want to start this process again until the user 12019 // explicitly does so... but for persistent process, we really 12020 // need to keep it running. If a persistent process is actually 12021 // repeatedly crashing, then badness for everyone. 12022 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid, 12023 app.info.processName); 12024 if (!app.isolated) { 12025 // XXX We don't have a way to mark isolated processes 12026 // as bad, since they don't have a peristent identity. 12027 mBadProcesses.put(app.info.processName, app.uid, 12028 new BadProcessInfo(now, shortMsg, longMsg, stackTrace)); 12029 mProcessCrashTimes.remove(app.info.processName, app.uid); 12030 } 12031 app.bad = true; 12032 app.removed = true; 12033 // Don't let services in this process be restarted and potentially 12034 // annoy the user repeatedly. Unless it is persistent, since those 12035 // processes run critical code. 12036 removeProcessLocked(app, false, false, "crash"); 12037 mStackSupervisor.resumeTopActivitiesLocked(); 12038 return false; 12039 } 12040 mStackSupervisor.resumeTopActivitiesLocked(); 12041 } else { 12042 mStackSupervisor.finishTopRunningActivityLocked(app, reason); 12043 } 12044 12045 // Bump up the crash count of any services currently running in the proc. 12046 for (int i=app.services.size()-1; i>=0; i--) { 12047 // Any services running in the application need to be placed 12048 // back in the pending list. 12049 ServiceRecord sr = app.services.valueAt(i); 12050 sr.crashCount++; 12051 } 12052 12053 // If the crashing process is what we consider to be the "home process" and it has been 12054 // replaced by a third-party app, clear the package preferred activities from packages 12055 // with a home activity running in the process to prevent a repeatedly crashing app 12056 // from blocking the user to manually clear the list. 12057 final ArrayList<ActivityRecord> activities = app.activities; 12058 if (app == mHomeProcess && activities.size() > 0 12059 && (mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) { 12060 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) { 12061 final ActivityRecord r = activities.get(activityNdx); 12062 if (r.isHomeActivity()) { 12063 Log.i(TAG, "Clearing package preferred activities from " + r.packageName); 12064 try { 12065 ActivityThread.getPackageManager() 12066 .clearPackagePreferredActivities(r.packageName); 12067 } catch (RemoteException c) { 12068 // pm is in same process, this will never happen. 12069 } 12070 } 12071 } 12072 } 12073 12074 if (!app.isolated) { 12075 // XXX Can't keep track of crash times for isolated processes, 12076 // because they don't have a perisistent identity. 12077 mProcessCrashTimes.put(app.info.processName, app.uid, now); 12078 } 12079 12080 if (app.crashHandler != null) mHandler.post(app.crashHandler); 12081 return true; 12082 } 12083 startAppProblemLocked(ProcessRecord app)12084 void startAppProblemLocked(ProcessRecord app) { 12085 // If this app is not running under the current user, then we 12086 // can't give it a report button because that would require 12087 // launching the report UI under a different user. 12088 app.errorReportReceiver = null; 12089 12090 for (int userId : mCurrentProfileIds) { 12091 if (app.userId == userId) { 12092 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver( 12093 mContext, app.info.packageName, app.info.flags); 12094 } 12095 } 12096 skipCurrentReceiverLocked(app); 12097 } 12098 skipCurrentReceiverLocked(ProcessRecord app)12099 void skipCurrentReceiverLocked(ProcessRecord app) { 12100 for (BroadcastQueue queue : mBroadcastQueues) { 12101 queue.skipCurrentReceiverLocked(app); 12102 } 12103 } 12104 12105 /** 12106 * Used by {@link com.android.internal.os.RuntimeInit} to report when an application crashes. 12107 * The application process will exit immediately after this call returns. 12108 * @param app object of the crashing app, null for the system server 12109 * @param crashInfo describing the exception 12110 */ handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo)12111 public void handleApplicationCrash(IBinder app, ApplicationErrorReport.CrashInfo crashInfo) { 12112 ProcessRecord r = findAppProcess(app, "Crash"); 12113 final String processName = app == null ? "system_server" 12114 : (r == null ? "unknown" : r.processName); 12115 12116 handleApplicationCrashInner("crash", r, processName, crashInfo); 12117 } 12118 12119 /* Native crash reporting uses this inner version because it needs to be somewhat 12120 * decoupled from the AM-managed cleanup lifecycle 12121 */ handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, ApplicationErrorReport.CrashInfo crashInfo)12122 void handleApplicationCrashInner(String eventType, ProcessRecord r, String processName, 12123 ApplicationErrorReport.CrashInfo crashInfo) { 12124 EventLog.writeEvent(EventLogTags.AM_CRASH, Binder.getCallingPid(), 12125 UserHandle.getUserId(Binder.getCallingUid()), processName, 12126 r == null ? -1 : r.info.flags, 12127 crashInfo.exceptionClassName, 12128 crashInfo.exceptionMessage, 12129 crashInfo.throwFileName, 12130 crashInfo.throwLineNumber); 12131 12132 addErrorToDropBox(eventType, r, processName, null, null, null, null, null, crashInfo); 12133 12134 crashApplication(r, crashInfo); 12135 } 12136 handleApplicationStrictModeViolation( IBinder app, int violationMask, StrictMode.ViolationInfo info)12137 public void handleApplicationStrictModeViolation( 12138 IBinder app, 12139 int violationMask, 12140 StrictMode.ViolationInfo info) { 12141 ProcessRecord r = findAppProcess(app, "StrictMode"); 12142 if (r == null) { 12143 return; 12144 } 12145 12146 if ((violationMask & StrictMode.PENALTY_DROPBOX) != 0) { 12147 Integer stackFingerprint = info.hashCode(); 12148 boolean logIt = true; 12149 synchronized (mAlreadyLoggedViolatedStacks) { 12150 if (mAlreadyLoggedViolatedStacks.contains(stackFingerprint)) { 12151 logIt = false; 12152 // TODO: sub-sample into EventLog for these, with 12153 // the info.durationMillis? Then we'd get 12154 // the relative pain numbers, without logging all 12155 // the stack traces repeatedly. We'd want to do 12156 // likewise in the client code, which also does 12157 // dup suppression, before the Binder call. 12158 } else { 12159 if (mAlreadyLoggedViolatedStacks.size() >= MAX_DUP_SUPPRESSED_STACKS) { 12160 mAlreadyLoggedViolatedStacks.clear(); 12161 } 12162 mAlreadyLoggedViolatedStacks.add(stackFingerprint); 12163 } 12164 } 12165 if (logIt) { 12166 logStrictModeViolationToDropBox(r, info); 12167 } 12168 } 12169 12170 if ((violationMask & StrictMode.PENALTY_DIALOG) != 0) { 12171 AppErrorResult result = new AppErrorResult(); 12172 synchronized (this) { 12173 final long origId = Binder.clearCallingIdentity(); 12174 12175 Message msg = Message.obtain(); 12176 msg.what = SHOW_STRICT_MODE_VIOLATION_MSG; 12177 HashMap<String, Object> data = new HashMap<String, Object>(); 12178 data.put("result", result); 12179 data.put("app", r); 12180 data.put("violationMask", violationMask); 12181 data.put("info", info); 12182 msg.obj = data; 12183 mUiHandler.sendMessage(msg); 12184 12185 Binder.restoreCallingIdentity(origId); 12186 } 12187 int res = result.get(); 12188 Slog.w(TAG, "handleApplicationStrictModeViolation; res=" + res); 12189 } 12190 } 12191 12192 // Depending on the policy in effect, there could be a bunch of 12193 // these in quick succession so we try to batch these together to 12194 // minimize disk writes, number of dropbox entries, and maximize 12195 // compression, by having more fewer, larger records. logStrictModeViolationToDropBox( ProcessRecord process, StrictMode.ViolationInfo info)12196 private void logStrictModeViolationToDropBox( 12197 ProcessRecord process, 12198 StrictMode.ViolationInfo info) { 12199 if (info == null) { 12200 return; 12201 } 12202 final boolean isSystemApp = process == null || 12203 (process.info.flags & (ApplicationInfo.FLAG_SYSTEM | 12204 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0; 12205 final String processName = process == null ? "unknown" : process.processName; 12206 final String dropboxTag = isSystemApp ? "system_app_strictmode" : "data_app_strictmode"; 12207 final DropBoxManager dbox = (DropBoxManager) 12208 mContext.getSystemService(Context.DROPBOX_SERVICE); 12209 12210 // Exit early if the dropbox isn't configured to accept this report type. 12211 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 12212 12213 boolean bufferWasEmpty; 12214 boolean needsFlush; 12215 final StringBuilder sb = isSystemApp ? mStrictModeBuffer : new StringBuilder(1024); 12216 synchronized (sb) { 12217 bufferWasEmpty = sb.length() == 0; 12218 appendDropBoxProcessHeaders(process, processName, sb); 12219 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 12220 sb.append("System-App: ").append(isSystemApp).append("\n"); 12221 sb.append("Uptime-Millis: ").append(info.violationUptimeMillis).append("\n"); 12222 if (info.violationNumThisLoop != 0) { 12223 sb.append("Loop-Violation-Number: ").append(info.violationNumThisLoop).append("\n"); 12224 } 12225 if (info.numAnimationsRunning != 0) { 12226 sb.append("Animations-Running: ").append(info.numAnimationsRunning).append("\n"); 12227 } 12228 if (info.broadcastIntentAction != null) { 12229 sb.append("Broadcast-Intent-Action: ").append(info.broadcastIntentAction).append("\n"); 12230 } 12231 if (info.durationMillis != -1) { 12232 sb.append("Duration-Millis: ").append(info.durationMillis).append("\n"); 12233 } 12234 if (info.numInstances != -1) { 12235 sb.append("Instance-Count: ").append(info.numInstances).append("\n"); 12236 } 12237 if (info.tags != null) { 12238 for (String tag : info.tags) { 12239 sb.append("Span-Tag: ").append(tag).append("\n"); 12240 } 12241 } 12242 sb.append("\n"); 12243 if (info.crashInfo != null && info.crashInfo.stackTrace != null) { 12244 sb.append(info.crashInfo.stackTrace); 12245 sb.append("\n"); 12246 } 12247 if (info.message != null) { 12248 sb.append(info.message); 12249 sb.append("\n"); 12250 } 12251 12252 // Only buffer up to ~64k. Various logging bits truncate 12253 // things at 128k. 12254 needsFlush = (sb.length() > 64 * 1024); 12255 } 12256 12257 // Flush immediately if the buffer's grown too large, or this 12258 // is a non-system app. Non-system apps are isolated with a 12259 // different tag & policy and not batched. 12260 // 12261 // Batching is useful during internal testing with 12262 // StrictMode settings turned up high. Without batching, 12263 // thousands of separate files could be created on boot. 12264 if (!isSystemApp || needsFlush) { 12265 new Thread("Error dump: " + dropboxTag) { 12266 @Override 12267 public void run() { 12268 String report; 12269 synchronized (sb) { 12270 report = sb.toString(); 12271 sb.delete(0, sb.length()); 12272 sb.trimToSize(); 12273 } 12274 if (report.length() != 0) { 12275 dbox.addText(dropboxTag, report); 12276 } 12277 } 12278 }.start(); 12279 return; 12280 } 12281 12282 // System app batching: 12283 if (!bufferWasEmpty) { 12284 // An existing dropbox-writing thread is outstanding, so 12285 // we don't need to start it up. The existing thread will 12286 // catch the buffer appends we just did. 12287 return; 12288 } 12289 12290 // Worker thread to both batch writes and to avoid blocking the caller on I/O. 12291 // (After this point, we shouldn't access AMS internal data structures.) 12292 new Thread("Error dump: " + dropboxTag) { 12293 @Override 12294 public void run() { 12295 // 5 second sleep to let stacks arrive and be batched together 12296 try { 12297 Thread.sleep(5000); // 5 seconds 12298 } catch (InterruptedException e) {} 12299 12300 String errorReport; 12301 synchronized (mStrictModeBuffer) { 12302 errorReport = mStrictModeBuffer.toString(); 12303 if (errorReport.length() == 0) { 12304 return; 12305 } 12306 mStrictModeBuffer.delete(0, mStrictModeBuffer.length()); 12307 mStrictModeBuffer.trimToSize(); 12308 } 12309 dbox.addText(dropboxTag, errorReport); 12310 } 12311 }.start(); 12312 } 12313 12314 /** 12315 * Used by {@link Log} via {@link com.android.internal.os.RuntimeInit} to report serious errors. 12316 * @param app object of the crashing app, null for the system server 12317 * @param tag reported by the caller 12318 * @param system whether this wtf is coming from the system 12319 * @param crashInfo describing the context of the error 12320 * @return true if the process should exit immediately (WTF is fatal) 12321 */ handleApplicationWtf(final IBinder app, final String tag, boolean system, final ApplicationErrorReport.CrashInfo crashInfo)12322 public boolean handleApplicationWtf(final IBinder app, final String tag, boolean system, 12323 final ApplicationErrorReport.CrashInfo crashInfo) { 12324 final int callingUid = Binder.getCallingUid(); 12325 final int callingPid = Binder.getCallingPid(); 12326 12327 if (system) { 12328 // If this is coming from the system, we could very well have low-level 12329 // system locks held, so we want to do this all asynchronously. And we 12330 // never want this to become fatal, so there is that too. 12331 mHandler.post(new Runnable() { 12332 @Override public void run() { 12333 handleApplicationWtfInner(callingUid, callingPid, app, tag, crashInfo); 12334 } 12335 }); 12336 return false; 12337 } 12338 12339 final ProcessRecord r = handleApplicationWtfInner(callingUid, callingPid, app, tag, 12340 crashInfo); 12341 12342 if (r != null && r.pid != Process.myPid() && 12343 Settings.Global.getInt(mContext.getContentResolver(), 12344 Settings.Global.WTF_IS_FATAL, 0) != 0) { 12345 crashApplication(r, crashInfo); 12346 return true; 12347 } else { 12348 return false; 12349 } 12350 } 12351 handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag, final ApplicationErrorReport.CrashInfo crashInfo)12352 ProcessRecord handleApplicationWtfInner(int callingUid, int callingPid, IBinder app, String tag, 12353 final ApplicationErrorReport.CrashInfo crashInfo) { 12354 final ProcessRecord r = findAppProcess(app, "WTF"); 12355 final String processName = app == null ? "system_server" 12356 : (r == null ? "unknown" : r.processName); 12357 12358 EventLog.writeEvent(EventLogTags.AM_WTF, UserHandle.getUserId(callingUid), callingPid, 12359 processName, r == null ? -1 : r.info.flags, tag, crashInfo.exceptionMessage); 12360 12361 addErrorToDropBox("wtf", r, processName, null, null, tag, null, null, crashInfo); 12362 12363 return r; 12364 } 12365 12366 /** 12367 * @param app object of some object (as stored in {@link com.android.internal.os.RuntimeInit}) 12368 * @return the corresponding {@link ProcessRecord} object, or null if none could be found 12369 */ findAppProcess(IBinder app, String reason)12370 private ProcessRecord findAppProcess(IBinder app, String reason) { 12371 if (app == null) { 12372 return null; 12373 } 12374 12375 synchronized (this) { 12376 final int NP = mProcessNames.getMap().size(); 12377 for (int ip=0; ip<NP; ip++) { 12378 SparseArray<ProcessRecord> apps = mProcessNames.getMap().valueAt(ip); 12379 final int NA = apps.size(); 12380 for (int ia=0; ia<NA; ia++) { 12381 ProcessRecord p = apps.valueAt(ia); 12382 if (p.thread != null && p.thread.asBinder() == app) { 12383 return p; 12384 } 12385 } 12386 } 12387 12388 Slog.w(TAG, "Can't find mystery application for " + reason 12389 + " from pid=" + Binder.getCallingPid() 12390 + " uid=" + Binder.getCallingUid() + ": " + app); 12391 return null; 12392 } 12393 } 12394 12395 /** 12396 * Utility function for addErrorToDropBox and handleStrictModeViolation's logging 12397 * to append various headers to the dropbox log text. 12398 */ appendDropBoxProcessHeaders(ProcessRecord process, String processName, StringBuilder sb)12399 private void appendDropBoxProcessHeaders(ProcessRecord process, String processName, 12400 StringBuilder sb) { 12401 // Watchdog thread ends up invoking this function (with 12402 // a null ProcessRecord) to add the stack file to dropbox. 12403 // Do not acquire a lock on this (am) in such cases, as it 12404 // could cause a potential deadlock, if and when watchdog 12405 // is invoked due to unavailability of lock on am and it 12406 // would prevent watchdog from killing system_server. 12407 if (process == null) { 12408 sb.append("Process: ").append(processName).append("\n"); 12409 return; 12410 } 12411 // Note: ProcessRecord 'process' is guarded by the service 12412 // instance. (notably process.pkgList, which could otherwise change 12413 // concurrently during execution of this method) 12414 synchronized (this) { 12415 sb.append("Process: ").append(processName).append("\n"); 12416 int flags = process.info.flags; 12417 IPackageManager pm = AppGlobals.getPackageManager(); 12418 sb.append("Flags: 0x").append(Integer.toString(flags, 16)).append("\n"); 12419 for (int ip=0; ip<process.pkgList.size(); ip++) { 12420 String pkg = process.pkgList.keyAt(ip); 12421 sb.append("Package: ").append(pkg); 12422 try { 12423 PackageInfo pi = pm.getPackageInfo(pkg, 0, UserHandle.getCallingUserId()); 12424 if (pi != null) { 12425 sb.append(" v").append(pi.versionCode); 12426 if (pi.versionName != null) { 12427 sb.append(" (").append(pi.versionName).append(")"); 12428 } 12429 } 12430 } catch (RemoteException e) { 12431 Slog.e(TAG, "Error getting package info: " + pkg, e); 12432 } 12433 sb.append("\n"); 12434 } 12435 } 12436 } 12437 processClass(ProcessRecord process)12438 private static String processClass(ProcessRecord process) { 12439 if (process == null || process.pid == MY_PID) { 12440 return "system_server"; 12441 } else if ((process.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12442 return "system_app"; 12443 } else { 12444 return "data_app"; 12445 } 12446 } 12447 12448 /** 12449 * Write a description of an error (crash, WTF, ANR) to the drop box. 12450 * @param eventType to include in the drop box tag ("crash", "wtf", etc.) 12451 * @param process which caused the error, null means the system server 12452 * @param activity which triggered the error, null if unknown 12453 * @param parent activity related to the error, null if unknown 12454 * @param subject line related to the error, null if absent 12455 * @param report in long form describing the error, null if absent 12456 * @param logFile to include in the report, null if none 12457 * @param crashInfo giving an application stack trace, null if absent 12458 */ addErrorToDropBox(String eventType, ProcessRecord process, String processName, ActivityRecord activity, ActivityRecord parent, String subject, final String report, final File logFile, final ApplicationErrorReport.CrashInfo crashInfo)12459 public void addErrorToDropBox(String eventType, 12460 ProcessRecord process, String processName, ActivityRecord activity, 12461 ActivityRecord parent, String subject, 12462 final String report, final File logFile, 12463 final ApplicationErrorReport.CrashInfo crashInfo) { 12464 // NOTE -- this must never acquire the ActivityManagerService lock, 12465 // otherwise the watchdog may be prevented from resetting the system. 12466 12467 final String dropboxTag = processClass(process) + "_" + eventType; 12468 final DropBoxManager dbox = (DropBoxManager) 12469 mContext.getSystemService(Context.DROPBOX_SERVICE); 12470 12471 // Exit early if the dropbox isn't configured to accept this report type. 12472 if (dbox == null || !dbox.isTagEnabled(dropboxTag)) return; 12473 12474 final StringBuilder sb = new StringBuilder(1024); 12475 appendDropBoxProcessHeaders(process, processName, sb); 12476 if (activity != null) { 12477 sb.append("Activity: ").append(activity.shortComponentName).append("\n"); 12478 } 12479 if (parent != null && parent.app != null && parent.app.pid != process.pid) { 12480 sb.append("Parent-Process: ").append(parent.app.processName).append("\n"); 12481 } 12482 if (parent != null && parent != activity) { 12483 sb.append("Parent-Activity: ").append(parent.shortComponentName).append("\n"); 12484 } 12485 if (subject != null) { 12486 sb.append("Subject: ").append(subject).append("\n"); 12487 } 12488 sb.append("Build: ").append(Build.FINGERPRINT).append("\n"); 12489 if (Debug.isDebuggerConnected()) { 12490 sb.append("Debugger: Connected\n"); 12491 } 12492 sb.append("\n"); 12493 12494 // Do the rest in a worker thread to avoid blocking the caller on I/O 12495 // (After this point, we shouldn't access AMS internal data structures.) 12496 Thread worker = new Thread("Error dump: " + dropboxTag) { 12497 @Override 12498 public void run() { 12499 if (report != null) { 12500 sb.append(report); 12501 } 12502 if (logFile != null) { 12503 try { 12504 sb.append(FileUtils.readTextFile(logFile, DROPBOX_MAX_SIZE, 12505 "\n\n[[TRUNCATED]]")); 12506 } catch (IOException e) { 12507 Slog.e(TAG, "Error reading " + logFile, e); 12508 } 12509 } 12510 if (crashInfo != null && crashInfo.stackTrace != null) { 12511 sb.append(crashInfo.stackTrace); 12512 } 12513 12514 String setting = Settings.Global.ERROR_LOGCAT_PREFIX + dropboxTag; 12515 int lines = Settings.Global.getInt(mContext.getContentResolver(), setting, 0); 12516 if (lines > 0) { 12517 sb.append("\n"); 12518 12519 // Merge several logcat streams, and take the last N lines 12520 InputStreamReader input = null; 12521 try { 12522 java.lang.Process logcat = new ProcessBuilder("/system/bin/logcat", 12523 "-v", "time", "-b", "events", "-b", "system", "-b", "main", 12524 "-b", "crash", 12525 "-t", String.valueOf(lines)).redirectErrorStream(true).start(); 12526 12527 try { logcat.getOutputStream().close(); } catch (IOException e) {} 12528 try { logcat.getErrorStream().close(); } catch (IOException e) {} 12529 input = new InputStreamReader(logcat.getInputStream()); 12530 12531 int num; 12532 char[] buf = new char[8192]; 12533 while ((num = input.read(buf)) > 0) sb.append(buf, 0, num); 12534 } catch (IOException e) { 12535 Slog.e(TAG, "Error running logcat", e); 12536 } finally { 12537 if (input != null) try { input.close(); } catch (IOException e) {} 12538 } 12539 } 12540 12541 dbox.addText(dropboxTag, sb.toString()); 12542 } 12543 }; 12544 12545 if (process == null) { 12546 // If process is null, we are being called from some internal code 12547 // and may be about to die -- run this synchronously. 12548 worker.run(); 12549 } else { 12550 worker.start(); 12551 } 12552 } 12553 12554 /** 12555 * Bring up the "unexpected error" dialog box for a crashing app. 12556 * Deal with edge cases (intercepts from instrumented applications, 12557 * ActivityController, error intent receivers, that sort of thing). 12558 * @param r the application crashing 12559 * @param crashInfo describing the failure 12560 */ crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo)12561 private void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) { 12562 long timeMillis = System.currentTimeMillis(); 12563 String shortMsg = crashInfo.exceptionClassName; 12564 String longMsg = crashInfo.exceptionMessage; 12565 String stackTrace = crashInfo.stackTrace; 12566 if (shortMsg != null && longMsg != null) { 12567 longMsg = shortMsg + ": " + longMsg; 12568 } else if (shortMsg != null) { 12569 longMsg = shortMsg; 12570 } 12571 12572 AppErrorResult result = new AppErrorResult(); 12573 synchronized (this) { 12574 if (mController != null) { 12575 try { 12576 String name = r != null ? r.processName : null; 12577 int pid = r != null ? r.pid : Binder.getCallingPid(); 12578 int uid = r != null ? r.info.uid : Binder.getCallingUid(); 12579 if (!mController.appCrashed(name, pid, 12580 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) { 12581 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")) 12582 && "Native crash".equals(crashInfo.exceptionClassName)) { 12583 Slog.w(TAG, "Skip killing native crashed app " + name 12584 + "(" + pid + ") during testing"); 12585 } else { 12586 Slog.w(TAG, "Force-killing crashed app " + name 12587 + " at watcher's request"); 12588 if (r != null) { 12589 r.kill("crash", true); 12590 } else { 12591 // Huh. 12592 Process.killProcess(pid); 12593 killProcessGroup(uid, pid); 12594 } 12595 } 12596 return; 12597 } 12598 } catch (RemoteException e) { 12599 mController = null; 12600 Watchdog.getInstance().setActivityController(null); 12601 } 12602 } 12603 12604 final long origId = Binder.clearCallingIdentity(); 12605 12606 // If this process is running instrumentation, finish it. 12607 if (r != null && r.instrumentationClass != null) { 12608 Slog.w(TAG, "Error in app " + r.processName 12609 + " running instrumentation " + r.instrumentationClass + ":"); 12610 if (shortMsg != null) Slog.w(TAG, " " + shortMsg); 12611 if (longMsg != null) Slog.w(TAG, " " + longMsg); 12612 Bundle info = new Bundle(); 12613 info.putString("shortMsg", shortMsg); 12614 info.putString("longMsg", longMsg); 12615 finishInstrumentationLocked(r, Activity.RESULT_CANCELED, info); 12616 Binder.restoreCallingIdentity(origId); 12617 return; 12618 } 12619 12620 // Log crash in battery stats. 12621 if (r != null) { 12622 mBatteryStatsService.noteProcessCrash(r.processName, r.uid); 12623 } 12624 12625 // If we can't identify the process or it's already exceeded its crash quota, 12626 // quit right away without showing a crash dialog. 12627 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace)) { 12628 Binder.restoreCallingIdentity(origId); 12629 return; 12630 } 12631 12632 Message msg = Message.obtain(); 12633 msg.what = SHOW_ERROR_MSG; 12634 HashMap data = new HashMap(); 12635 data.put("result", result); 12636 data.put("app", r); 12637 msg.obj = data; 12638 mUiHandler.sendMessage(msg); 12639 12640 Binder.restoreCallingIdentity(origId); 12641 } 12642 12643 int res = result.get(); 12644 12645 Intent appErrorIntent = null; 12646 synchronized (this) { 12647 if (r != null && !r.isolated) { 12648 // XXX Can't keep track of crash time for isolated processes, 12649 // since they don't have a persistent identity. 12650 mProcessCrashTimes.put(r.info.processName, r.uid, 12651 SystemClock.uptimeMillis()); 12652 } 12653 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) { 12654 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo); 12655 } 12656 } 12657 12658 if (appErrorIntent != null) { 12659 try { 12660 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId)); 12661 } catch (ActivityNotFoundException e) { 12662 Slog.w(TAG, "bug report receiver dissappeared", e); 12663 } 12664 } 12665 } 12666 createAppErrorIntentLocked(ProcessRecord r, long timeMillis, ApplicationErrorReport.CrashInfo crashInfo)12667 Intent createAppErrorIntentLocked(ProcessRecord r, 12668 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) { 12669 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo); 12670 if (report == null) { 12671 return null; 12672 } 12673 Intent result = new Intent(Intent.ACTION_APP_ERROR); 12674 result.setComponent(r.errorReportReceiver); 12675 result.putExtra(Intent.EXTRA_BUG_REPORT, report); 12676 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 12677 return result; 12678 } 12679 createAppErrorReportLocked(ProcessRecord r, long timeMillis, ApplicationErrorReport.CrashInfo crashInfo)12680 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r, 12681 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) { 12682 if (r.errorReportReceiver == null) { 12683 return null; 12684 } 12685 12686 if (!r.crashing && !r.notResponding && !r.forceCrashReport) { 12687 return null; 12688 } 12689 12690 ApplicationErrorReport report = new ApplicationErrorReport(); 12691 report.packageName = r.info.packageName; 12692 report.installerPackageName = r.errorReportReceiver.getPackageName(); 12693 report.processName = r.processName; 12694 report.time = timeMillis; 12695 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 12696 12697 if (r.crashing || r.forceCrashReport) { 12698 report.type = ApplicationErrorReport.TYPE_CRASH; 12699 report.crashInfo = crashInfo; 12700 } else if (r.notResponding) { 12701 report.type = ApplicationErrorReport.TYPE_ANR; 12702 report.anrInfo = new ApplicationErrorReport.AnrInfo(); 12703 12704 report.anrInfo.activity = r.notRespondingReport.tag; 12705 report.anrInfo.cause = r.notRespondingReport.shortMsg; 12706 report.anrInfo.info = r.notRespondingReport.longMsg; 12707 } 12708 12709 return report; 12710 } 12711 getProcessesInErrorState()12712 public List<ActivityManager.ProcessErrorStateInfo> getProcessesInErrorState() { 12713 enforceNotIsolatedCaller("getProcessesInErrorState"); 12714 // assume our apps are happy - lazy create the list 12715 List<ActivityManager.ProcessErrorStateInfo> errList = null; 12716 12717 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 12718 Binder.getCallingUid()) == PackageManager.PERMISSION_GRANTED; 12719 int userId = UserHandle.getUserId(Binder.getCallingUid()); 12720 12721 synchronized (this) { 12722 12723 // iterate across all processes 12724 for (int i=mLruProcesses.size()-1; i>=0; i--) { 12725 ProcessRecord app = mLruProcesses.get(i); 12726 if (!allUsers && app.userId != userId) { 12727 continue; 12728 } 12729 if ((app.thread != null) && (app.crashing || app.notResponding)) { 12730 // This one's in trouble, so we'll generate a report for it 12731 // crashes are higher priority (in case there's a crash *and* an anr) 12732 ActivityManager.ProcessErrorStateInfo report = null; 12733 if (app.crashing) { 12734 report = app.crashingReport; 12735 } else if (app.notResponding) { 12736 report = app.notRespondingReport; 12737 } 12738 12739 if (report != null) { 12740 if (errList == null) { 12741 errList = new ArrayList<ActivityManager.ProcessErrorStateInfo>(1); 12742 } 12743 errList.add(report); 12744 } else { 12745 Slog.w(TAG, "Missing app error report, app = " + app.processName + 12746 " crashing = " + app.crashing + 12747 " notResponding = " + app.notResponding); 12748 } 12749 } 12750 } 12751 } 12752 12753 return errList; 12754 } 12755 procStateToImportance(int procState, int memAdj, ActivityManager.RunningAppProcessInfo currApp)12756 static int procStateToImportance(int procState, int memAdj, 12757 ActivityManager.RunningAppProcessInfo currApp) { 12758 int imp = ActivityManager.RunningAppProcessInfo.procStateToImportance(procState); 12759 if (imp == ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) { 12760 currApp.lru = memAdj; 12761 } else { 12762 currApp.lru = 0; 12763 } 12764 return imp; 12765 } 12766 fillInProcMemInfo(ProcessRecord app, ActivityManager.RunningAppProcessInfo outInfo)12767 private void fillInProcMemInfo(ProcessRecord app, 12768 ActivityManager.RunningAppProcessInfo outInfo) { 12769 outInfo.pid = app.pid; 12770 outInfo.uid = app.info.uid; 12771 if (mHeavyWeightProcess == app) { 12772 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_CANT_SAVE_STATE; 12773 } 12774 if (app.persistent) { 12775 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_PERSISTENT; 12776 } 12777 if (app.activities.size() > 0) { 12778 outInfo.flags |= ActivityManager.RunningAppProcessInfo.FLAG_HAS_ACTIVITIES; 12779 } 12780 outInfo.lastTrimLevel = app.trimMemoryLevel; 12781 int adj = app.curAdj; 12782 int procState = app.curProcState; 12783 outInfo.importance = procStateToImportance(procState, adj, outInfo); 12784 outInfo.importanceReasonCode = app.adjTypeCode; 12785 outInfo.processState = app.curProcState; 12786 } 12787 getRunningAppProcesses()12788 public List<ActivityManager.RunningAppProcessInfo> getRunningAppProcesses() { 12789 enforceNotIsolatedCaller("getRunningAppProcesses"); 12790 12791 final int callingUid = Binder.getCallingUid(); 12792 12793 // Lazy instantiation of list 12794 List<ActivityManager.RunningAppProcessInfo> runList = null; 12795 final boolean allUsers = ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, 12796 callingUid) == PackageManager.PERMISSION_GRANTED; 12797 final int userId = UserHandle.getUserId(callingUid); 12798 final boolean allUids = isGetTasksAllowed( 12799 "getRunningAppProcesses", Binder.getCallingPid(), callingUid); 12800 12801 synchronized (this) { 12802 // Iterate across all processes 12803 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 12804 ProcessRecord app = mLruProcesses.get(i); 12805 if ((!allUsers && app.userId != userId) 12806 || (!allUids && app.uid != callingUid)) { 12807 continue; 12808 } 12809 if ((app.thread != null) && (!app.crashing && !app.notResponding)) { 12810 // Generate process state info for running application 12811 ActivityManager.RunningAppProcessInfo currApp = 12812 new ActivityManager.RunningAppProcessInfo(app.processName, 12813 app.pid, app.getPackageList()); 12814 fillInProcMemInfo(app, currApp); 12815 if (app.adjSource instanceof ProcessRecord) { 12816 currApp.importanceReasonPid = ((ProcessRecord)app.adjSource).pid; 12817 currApp.importanceReasonImportance = 12818 ActivityManager.RunningAppProcessInfo.procStateToImportance( 12819 app.adjSourceProcState); 12820 } else if (app.adjSource instanceof ActivityRecord) { 12821 ActivityRecord r = (ActivityRecord)app.adjSource; 12822 if (r.app != null) currApp.importanceReasonPid = r.app.pid; 12823 } 12824 if (app.adjTarget instanceof ComponentName) { 12825 currApp.importanceReasonComponent = (ComponentName)app.adjTarget; 12826 } 12827 //Slog.v(TAG, "Proc " + app.processName + ": imp=" + currApp.importance 12828 // + " lru=" + currApp.lru); 12829 if (runList == null) { 12830 runList = new ArrayList<>(); 12831 } 12832 runList.add(currApp); 12833 } 12834 } 12835 } 12836 return runList; 12837 } 12838 getRunningExternalApplications()12839 public List<ApplicationInfo> getRunningExternalApplications() { 12840 enforceNotIsolatedCaller("getRunningExternalApplications"); 12841 List<ActivityManager.RunningAppProcessInfo> runningApps = getRunningAppProcesses(); 12842 List<ApplicationInfo> retList = new ArrayList<ApplicationInfo>(); 12843 if (runningApps != null && runningApps.size() > 0) { 12844 Set<String> extList = new HashSet<String>(); 12845 for (ActivityManager.RunningAppProcessInfo app : runningApps) { 12846 if (app.pkgList != null) { 12847 for (String pkg : app.pkgList) { 12848 extList.add(pkg); 12849 } 12850 } 12851 } 12852 IPackageManager pm = AppGlobals.getPackageManager(); 12853 for (String pkg : extList) { 12854 try { 12855 ApplicationInfo info = pm.getApplicationInfo(pkg, 0, UserHandle.getCallingUserId()); 12856 if ((info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0) { 12857 retList.add(info); 12858 } 12859 } catch (RemoteException e) { 12860 } 12861 } 12862 } 12863 return retList; 12864 } 12865 12866 @Override getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo)12867 public void getMyMemoryState(ActivityManager.RunningAppProcessInfo outInfo) { 12868 enforceNotIsolatedCaller("getMyMemoryState"); 12869 synchronized (this) { 12870 ProcessRecord proc; 12871 synchronized (mPidsSelfLocked) { 12872 proc = mPidsSelfLocked.get(Binder.getCallingPid()); 12873 } 12874 fillInProcMemInfo(proc, outInfo); 12875 } 12876 } 12877 12878 @Override dump(FileDescriptor fd, PrintWriter pw, String[] args)12879 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 12880 if (checkCallingPermission(android.Manifest.permission.DUMP) 12881 != PackageManager.PERMISSION_GRANTED) { 12882 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 12883 + Binder.getCallingPid() 12884 + ", uid=" + Binder.getCallingUid() 12885 + " without permission " 12886 + android.Manifest.permission.DUMP); 12887 return; 12888 } 12889 12890 boolean dumpAll = false; 12891 boolean dumpClient = false; 12892 String dumpPackage = null; 12893 12894 int opti = 0; 12895 while (opti < args.length) { 12896 String opt = args[opti]; 12897 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 12898 break; 12899 } 12900 opti++; 12901 if ("-a".equals(opt)) { 12902 dumpAll = true; 12903 } else if ("-c".equals(opt)) { 12904 dumpClient = true; 12905 } else if ("-p".equals(opt)) { 12906 if (opti < args.length) { 12907 dumpPackage = args[opti]; 12908 opti++; 12909 } else { 12910 pw.println("Error: -p option requires package argument"); 12911 return; 12912 } 12913 dumpClient = true; 12914 } else if ("-h".equals(opt)) { 12915 pw.println("Activity manager dump options:"); 12916 pw.println(" [-a] [-c] [-p package] [-h] [cmd] ..."); 12917 pw.println(" cmd may be one of:"); 12918 pw.println(" a[ctivities]: activity stack state"); 12919 pw.println(" r[recents]: recent activities state"); 12920 pw.println(" b[roadcasts] [PACKAGE_NAME] [history [-s]]: broadcast state"); 12921 pw.println(" i[ntents] [PACKAGE_NAME]: pending intent state"); 12922 pw.println(" p[rocesses] [PACKAGE_NAME]: process state"); 12923 pw.println(" o[om]: out of memory management"); 12924 pw.println(" perm[issions]: URI permission grant state"); 12925 pw.println(" prov[iders] [COMP_SPEC ...]: content provider state"); 12926 pw.println(" provider [COMP_SPEC]: provider client-side state"); 12927 pw.println(" s[ervices] [COMP_SPEC ...]: service state"); 12928 pw.println(" as[sociations]: tracked app associations"); 12929 pw.println(" service [COMP_SPEC]: service client-side state"); 12930 pw.println(" package [PACKAGE_NAME]: all state related to given package"); 12931 pw.println(" all: dump all activities"); 12932 pw.println(" top: dump the top activity"); 12933 pw.println(" write: write all pending state to storage"); 12934 pw.println(" track-associations: enable association tracking"); 12935 pw.println(" untrack-associations: disable and clear association tracking"); 12936 pw.println(" cmd may also be a COMP_SPEC to dump activities."); 12937 pw.println(" COMP_SPEC may be a component name (com.foo/.myApp),"); 12938 pw.println(" a partial substring in a component name, a"); 12939 pw.println(" hex object identifier."); 12940 pw.println(" -a: include all available server state."); 12941 pw.println(" -c: include client state."); 12942 pw.println(" -p: limit output to given package."); 12943 return; 12944 } else { 12945 pw.println("Unknown argument: " + opt + "; use -h for help"); 12946 } 12947 } 12948 12949 long origId = Binder.clearCallingIdentity(); 12950 boolean more = false; 12951 // Is the caller requesting to dump a particular piece of data? 12952 if (opti < args.length) { 12953 String cmd = args[opti]; 12954 opti++; 12955 if ("activities".equals(cmd) || "a".equals(cmd)) { 12956 synchronized (this) { 12957 dumpActivitiesLocked(fd, pw, args, opti, true, dumpClient, dumpPackage); 12958 } 12959 } else if ("recents".equals(cmd) || "r".equals(cmd)) { 12960 synchronized (this) { 12961 dumpRecentsLocked(fd, pw, args, opti, true, dumpPackage); 12962 } 12963 } else if ("broadcasts".equals(cmd) || "b".equals(cmd)) { 12964 String[] newArgs; 12965 String name; 12966 if (opti >= args.length) { 12967 name = null; 12968 newArgs = EMPTY_STRING_ARRAY; 12969 } else { 12970 dumpPackage = args[opti]; 12971 opti++; 12972 newArgs = new String[args.length - opti]; 12973 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12974 args.length - opti); 12975 } 12976 synchronized (this) { 12977 dumpBroadcastsLocked(fd, pw, args, opti, true, dumpPackage); 12978 } 12979 } else if ("intents".equals(cmd) || "i".equals(cmd)) { 12980 String[] newArgs; 12981 String name; 12982 if (opti >= args.length) { 12983 name = null; 12984 newArgs = EMPTY_STRING_ARRAY; 12985 } else { 12986 dumpPackage = args[opti]; 12987 opti++; 12988 newArgs = new String[args.length - opti]; 12989 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 12990 args.length - opti); 12991 } 12992 synchronized (this) { 12993 dumpPendingIntentsLocked(fd, pw, args, opti, true, dumpPackage); 12994 } 12995 } else if ("processes".equals(cmd) || "p".equals(cmd)) { 12996 String[] newArgs; 12997 String name; 12998 if (opti >= args.length) { 12999 name = null; 13000 newArgs = EMPTY_STRING_ARRAY; 13001 } else { 13002 dumpPackage = args[opti]; 13003 opti++; 13004 newArgs = new String[args.length - opti]; 13005 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 13006 args.length - opti); 13007 } 13008 synchronized (this) { 13009 dumpProcessesLocked(fd, pw, args, opti, true, dumpPackage); 13010 } 13011 } else if ("oom".equals(cmd) || "o".equals(cmd)) { 13012 synchronized (this) { 13013 dumpOomLocked(fd, pw, args, opti, true); 13014 } 13015 } else if ("permissions".equals(cmd) || "perm".equals(cmd)) { 13016 synchronized (this) { 13017 dumpPermissionsLocked(fd, pw, args, opti, true, null); 13018 } 13019 } else if ("provider".equals(cmd)) { 13020 String[] newArgs; 13021 String name; 13022 if (opti >= args.length) { 13023 name = null; 13024 newArgs = EMPTY_STRING_ARRAY; 13025 } else { 13026 name = args[opti]; 13027 opti++; 13028 newArgs = new String[args.length - opti]; 13029 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, args.length - opti); 13030 } 13031 if (!dumpProvider(fd, pw, name, newArgs, 0, dumpAll)) { 13032 pw.println("No providers match: " + name); 13033 pw.println("Use -h for help."); 13034 } 13035 } else if ("providers".equals(cmd) || "prov".equals(cmd)) { 13036 synchronized (this) { 13037 dumpProvidersLocked(fd, pw, args, opti, true, null); 13038 } 13039 } else if ("service".equals(cmd)) { 13040 String[] newArgs; 13041 String name; 13042 if (opti >= args.length) { 13043 name = null; 13044 newArgs = EMPTY_STRING_ARRAY; 13045 } else { 13046 name = args[opti]; 13047 opti++; 13048 newArgs = new String[args.length - opti]; 13049 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 13050 args.length - opti); 13051 } 13052 if (!mServices.dumpService(fd, pw, name, newArgs, 0, dumpAll)) { 13053 pw.println("No services match: " + name); 13054 pw.println("Use -h for help."); 13055 } 13056 } else if ("package".equals(cmd)) { 13057 String[] newArgs; 13058 if (opti >= args.length) { 13059 pw.println("package: no package name specified"); 13060 pw.println("Use -h for help."); 13061 } else { 13062 dumpPackage = args[opti]; 13063 opti++; 13064 newArgs = new String[args.length - opti]; 13065 if (args.length > 2) System.arraycopy(args, opti, newArgs, 0, 13066 args.length - opti); 13067 args = newArgs; 13068 opti = 0; 13069 more = true; 13070 } 13071 } else if ("associations".equals(cmd) || "as".equals(cmd)) { 13072 synchronized (this) { 13073 dumpAssociationsLocked(fd, pw, args, opti, true, dumpClient, dumpPackage); 13074 } 13075 } else if ("services".equals(cmd) || "s".equals(cmd)) { 13076 synchronized (this) { 13077 mServices.dumpServicesLocked(fd, pw, args, opti, true, dumpClient, dumpPackage); 13078 } 13079 } else if ("write".equals(cmd)) { 13080 mTaskPersister.flush(); 13081 pw.println("All tasks persisted."); 13082 return; 13083 } else if ("track-associations".equals(cmd)) { 13084 synchronized (this) { 13085 if (!mTrackingAssociations) { 13086 mTrackingAssociations = true; 13087 pw.println("Association tracking started."); 13088 } else { 13089 pw.println("Association tracking already enabled."); 13090 } 13091 } 13092 return; 13093 } else if ("untrack-associations".equals(cmd)) { 13094 synchronized (this) { 13095 if (mTrackingAssociations) { 13096 mTrackingAssociations = false; 13097 mAssociations.clear(); 13098 pw.println("Association tracking stopped."); 13099 } else { 13100 pw.println("Association tracking not running."); 13101 } 13102 } 13103 return; 13104 } else { 13105 // Dumping a single activity? 13106 if (!dumpActivity(fd, pw, cmd, args, opti, dumpAll)) { 13107 pw.println("Bad activity command, or no activities match: " + cmd); 13108 pw.println("Use -h for help."); 13109 } 13110 } 13111 if (!more) { 13112 Binder.restoreCallingIdentity(origId); 13113 return; 13114 } 13115 } 13116 13117 // No piece of data specified, dump everything. 13118 synchronized (this) { 13119 dumpPendingIntentsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 13120 pw.println(); 13121 if (dumpAll) { 13122 pw.println("-------------------------------------------------------------------------------"); 13123 } 13124 dumpBroadcastsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 13125 pw.println(); 13126 if (dumpAll) { 13127 pw.println("-------------------------------------------------------------------------------"); 13128 } 13129 dumpProvidersLocked(fd, pw, args, opti, dumpAll, dumpPackage); 13130 pw.println(); 13131 if (dumpAll) { 13132 pw.println("-------------------------------------------------------------------------------"); 13133 } 13134 dumpPermissionsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 13135 pw.println(); 13136 if (dumpAll) { 13137 pw.println("-------------------------------------------------------------------------------"); 13138 } 13139 mServices.dumpServicesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 13140 pw.println(); 13141 if (dumpAll) { 13142 pw.println("-------------------------------------------------------------------------------"); 13143 } 13144 dumpRecentsLocked(fd, pw, args, opti, dumpAll, dumpPackage); 13145 pw.println(); 13146 if (dumpAll) { 13147 pw.println("-------------------------------------------------------------------------------"); 13148 } 13149 dumpActivitiesLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 13150 if (mAssociations.size() > 0) { 13151 pw.println(); 13152 if (dumpAll) { 13153 pw.println("-------------------------------------------------------------------------------"); 13154 } 13155 dumpAssociationsLocked(fd, pw, args, opti, dumpAll, dumpClient, dumpPackage); 13156 } 13157 pw.println(); 13158 if (dumpAll) { 13159 pw.println("-------------------------------------------------------------------------------"); 13160 } 13161 dumpProcessesLocked(fd, pw, args, opti, dumpAll, dumpPackage); 13162 } 13163 Binder.restoreCallingIdentity(origId); 13164 } 13165 dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)13166 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13167 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 13168 pw.println("ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)"); 13169 13170 boolean printedAnything = mStackSupervisor.dumpActivitiesLocked(fd, pw, dumpAll, dumpClient, 13171 dumpPackage); 13172 boolean needSep = printedAnything; 13173 13174 boolean printed = ActivityStackSupervisor.printThisActivity(pw, mFocusedActivity, 13175 dumpPackage, needSep, " mFocusedActivity: "); 13176 if (printed) { 13177 printedAnything = true; 13178 needSep = false; 13179 } 13180 13181 if (dumpPackage == null) { 13182 if (needSep) { 13183 pw.println(); 13184 } 13185 needSep = true; 13186 printedAnything = true; 13187 mStackSupervisor.dump(pw, " "); 13188 } 13189 13190 if (!printedAnything) { 13191 pw.println(" (nothing)"); 13192 } 13193 } 13194 dumpRecentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)13195 void dumpRecentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13196 int opti, boolean dumpAll, String dumpPackage) { 13197 pw.println("ACTIVITY MANAGER RECENT TASKS (dumpsys activity recents)"); 13198 13199 boolean printedAnything = false; 13200 13201 if (mRecentTasks != null && mRecentTasks.size() > 0) { 13202 boolean printedHeader = false; 13203 13204 final int N = mRecentTasks.size(); 13205 for (int i=0; i<N; i++) { 13206 TaskRecord tr = mRecentTasks.get(i); 13207 if (dumpPackage != null) { 13208 if (tr.realActivity == null || 13209 !dumpPackage.equals(tr.realActivity)) { 13210 continue; 13211 } 13212 } 13213 if (!printedHeader) { 13214 pw.println(" Recent tasks:"); 13215 printedHeader = true; 13216 printedAnything = true; 13217 } 13218 pw.print(" * Recent #"); pw.print(i); pw.print(": "); 13219 pw.println(tr); 13220 if (dumpAll) { 13221 mRecentTasks.get(i).dump(pw, " "); 13222 } 13223 } 13224 } 13225 13226 if (!printedAnything) { 13227 pw.println(" (nothing)"); 13228 } 13229 } 13230 dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, boolean dumpClient, String dumpPackage)13231 void dumpAssociationsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13232 int opti, boolean dumpAll, boolean dumpClient, String dumpPackage) { 13233 pw.println("ACTIVITY MANAGER ASSOCIATIONS (dumpsys activity associations)"); 13234 13235 int dumpUid = 0; 13236 if (dumpPackage != null) { 13237 IPackageManager pm = AppGlobals.getPackageManager(); 13238 try { 13239 dumpUid = pm.getPackageUid(dumpPackage, 0); 13240 } catch (RemoteException e) { 13241 } 13242 } 13243 13244 boolean printedAnything = false; 13245 13246 final long now = SystemClock.uptimeMillis(); 13247 13248 for (int i1=0, N1=mAssociations.size(); i1<N1; i1++) { 13249 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> targetComponents 13250 = mAssociations.valueAt(i1); 13251 for (int i2=0, N2=targetComponents.size(); i2<N2; i2++) { 13252 SparseArray<ArrayMap<String, Association>> sourceUids 13253 = targetComponents.valueAt(i2); 13254 for (int i3=0, N3=sourceUids.size(); i3<N3; i3++) { 13255 ArrayMap<String, Association> sourceProcesses = sourceUids.valueAt(i3); 13256 for (int i4=0, N4=sourceProcesses.size(); i4<N4; i4++) { 13257 Association ass = sourceProcesses.valueAt(i4); 13258 if (dumpPackage != null) { 13259 if (!ass.mTargetComponent.getPackageName().equals(dumpPackage) 13260 && UserHandle.getAppId(ass.mSourceUid) != dumpUid) { 13261 continue; 13262 } 13263 } 13264 printedAnything = true; 13265 pw.print(" "); 13266 pw.print(ass.mTargetProcess); 13267 pw.print("/"); 13268 UserHandle.formatUid(pw, ass.mTargetUid); 13269 pw.print(" <- "); 13270 pw.print(ass.mSourceProcess); 13271 pw.print("/"); 13272 UserHandle.formatUid(pw, ass.mSourceUid); 13273 pw.println(); 13274 pw.print(" via "); 13275 pw.print(ass.mTargetComponent.flattenToShortString()); 13276 pw.println(); 13277 pw.print(" "); 13278 long dur = ass.mTime; 13279 if (ass.mNesting > 0) { 13280 dur += now - ass.mStartTime; 13281 } 13282 TimeUtils.formatDuration(dur, pw); 13283 pw.print(" ("); 13284 pw.print(ass.mCount); 13285 pw.println(" times)"); 13286 if (ass.mNesting > 0) { 13287 pw.print(" "); 13288 pw.print(" Currently active: "); 13289 TimeUtils.formatDuration(now - ass.mStartTime, pw); 13290 pw.println(); 13291 } 13292 } 13293 } 13294 } 13295 13296 } 13297 13298 if (!printedAnything) { 13299 pw.println(" (nothing)"); 13300 } 13301 } 13302 dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)13303 void dumpProcessesLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13304 int opti, boolean dumpAll, String dumpPackage) { 13305 boolean needSep = false; 13306 boolean printedAnything = false; 13307 int numPers = 0; 13308 13309 pw.println("ACTIVITY MANAGER RUNNING PROCESSES (dumpsys activity processes)"); 13310 13311 if (dumpAll) { 13312 final int NP = mProcessNames.getMap().size(); 13313 for (int ip=0; ip<NP; ip++) { 13314 SparseArray<ProcessRecord> procs = mProcessNames.getMap().valueAt(ip); 13315 final int NA = procs.size(); 13316 for (int ia=0; ia<NA; ia++) { 13317 ProcessRecord r = procs.valueAt(ia); 13318 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 13319 continue; 13320 } 13321 if (!needSep) { 13322 pw.println(" All known processes:"); 13323 needSep = true; 13324 printedAnything = true; 13325 } 13326 pw.print(r.persistent ? " *PERS*" : " *APP*"); 13327 pw.print(" UID "); pw.print(procs.keyAt(ia)); 13328 pw.print(" "); pw.println(r); 13329 r.dump(pw, " "); 13330 if (r.persistent) { 13331 numPers++; 13332 } 13333 } 13334 } 13335 } 13336 13337 if (mIsolatedProcesses.size() > 0) { 13338 boolean printed = false; 13339 for (int i=0; i<mIsolatedProcesses.size(); i++) { 13340 ProcessRecord r = mIsolatedProcesses.valueAt(i); 13341 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 13342 continue; 13343 } 13344 if (!printed) { 13345 if (needSep) { 13346 pw.println(); 13347 } 13348 pw.println(" Isolated process list (sorted by uid):"); 13349 printedAnything = true; 13350 printed = true; 13351 needSep = true; 13352 } 13353 pw.println(String.format("%sIsolated #%2d: %s", 13354 " ", i, r.toString())); 13355 } 13356 } 13357 13358 if (mActiveUids.size() > 0) { 13359 if (needSep) { 13360 pw.println(); 13361 } 13362 pw.println(" UID states:"); 13363 for (int i=0; i<mActiveUids.size(); i++) { 13364 UidRecord uidRec = mActiveUids.valueAt(i); 13365 pw.print(" UID "); UserHandle.formatUid(pw, uidRec.uid); 13366 pw.print(": "); pw.println(uidRec); 13367 } 13368 needSep = true; 13369 printedAnything = true; 13370 } 13371 13372 if (mLruProcesses.size() > 0) { 13373 if (needSep) { 13374 pw.println(); 13375 } 13376 pw.print(" Process LRU list (sorted by oom_adj, "); pw.print(mLruProcesses.size()); 13377 pw.print(" total, non-act at "); 13378 pw.print(mLruProcesses.size()-mLruProcessActivityStart); 13379 pw.print(", non-svc at "); 13380 pw.print(mLruProcesses.size()-mLruProcessServiceStart); 13381 pw.println("):"); 13382 dumpProcessOomList(pw, this, mLruProcesses, " ", "Proc", "PERS", false, dumpPackage); 13383 needSep = true; 13384 printedAnything = true; 13385 } 13386 13387 if (dumpAll || dumpPackage != null) { 13388 synchronized (mPidsSelfLocked) { 13389 boolean printed = false; 13390 for (int i=0; i<mPidsSelfLocked.size(); i++) { 13391 ProcessRecord r = mPidsSelfLocked.valueAt(i); 13392 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 13393 continue; 13394 } 13395 if (!printed) { 13396 if (needSep) pw.println(); 13397 needSep = true; 13398 pw.println(" PID mappings:"); 13399 printed = true; 13400 printedAnything = true; 13401 } 13402 pw.print(" PID #"); pw.print(mPidsSelfLocked.keyAt(i)); 13403 pw.print(": "); pw.println(mPidsSelfLocked.valueAt(i)); 13404 } 13405 } 13406 } 13407 13408 if (mForegroundProcesses.size() > 0) { 13409 synchronized (mPidsSelfLocked) { 13410 boolean printed = false; 13411 for (int i=0; i<mForegroundProcesses.size(); i++) { 13412 ProcessRecord r = mPidsSelfLocked.get( 13413 mForegroundProcesses.valueAt(i).pid); 13414 if (dumpPackage != null && (r == null 13415 || !r.pkgList.containsKey(dumpPackage))) { 13416 continue; 13417 } 13418 if (!printed) { 13419 if (needSep) pw.println(); 13420 needSep = true; 13421 pw.println(" Foreground Processes:"); 13422 printed = true; 13423 printedAnything = true; 13424 } 13425 pw.print(" PID #"); pw.print(mForegroundProcesses.keyAt(i)); 13426 pw.print(": "); pw.println(mForegroundProcesses.valueAt(i)); 13427 } 13428 } 13429 } 13430 13431 if (mPersistentStartingProcesses.size() > 0) { 13432 if (needSep) pw.println(); 13433 needSep = true; 13434 printedAnything = true; 13435 pw.println(" Persisent processes that are starting:"); 13436 dumpProcessList(pw, this, mPersistentStartingProcesses, " ", 13437 "Starting Norm", "Restarting PERS", dumpPackage); 13438 } 13439 13440 if (mRemovedProcesses.size() > 0) { 13441 if (needSep) pw.println(); 13442 needSep = true; 13443 printedAnything = true; 13444 pw.println(" Processes that are being removed:"); 13445 dumpProcessList(pw, this, mRemovedProcesses, " ", 13446 "Removed Norm", "Removed PERS", dumpPackage); 13447 } 13448 13449 if (mProcessesOnHold.size() > 0) { 13450 if (needSep) pw.println(); 13451 needSep = true; 13452 printedAnything = true; 13453 pw.println(" Processes that are on old until the system is ready:"); 13454 dumpProcessList(pw, this, mProcessesOnHold, " ", 13455 "OnHold Norm", "OnHold PERS", dumpPackage); 13456 } 13457 13458 needSep = dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, dumpPackage); 13459 13460 if (mProcessCrashTimes.getMap().size() > 0) { 13461 boolean printed = false; 13462 long now = SystemClock.uptimeMillis(); 13463 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap(); 13464 final int NP = pmap.size(); 13465 for (int ip=0; ip<NP; ip++) { 13466 String pname = pmap.keyAt(ip); 13467 SparseArray<Long> uids = pmap.valueAt(ip); 13468 final int N = uids.size(); 13469 for (int i=0; i<N; i++) { 13470 int puid = uids.keyAt(i); 13471 ProcessRecord r = mProcessNames.get(pname, puid); 13472 if (dumpPackage != null && (r == null 13473 || !r.pkgList.containsKey(dumpPackage))) { 13474 continue; 13475 } 13476 if (!printed) { 13477 if (needSep) pw.println(); 13478 needSep = true; 13479 pw.println(" Time since processes crashed:"); 13480 printed = true; 13481 printedAnything = true; 13482 } 13483 pw.print(" Process "); pw.print(pname); 13484 pw.print(" uid "); pw.print(puid); 13485 pw.print(": last crashed "); 13486 TimeUtils.formatDuration(now-uids.valueAt(i), pw); 13487 pw.println(" ago"); 13488 } 13489 } 13490 } 13491 13492 if (mBadProcesses.getMap().size() > 0) { 13493 boolean printed = false; 13494 final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap(); 13495 final int NP = pmap.size(); 13496 for (int ip=0; ip<NP; ip++) { 13497 String pname = pmap.keyAt(ip); 13498 SparseArray<BadProcessInfo> uids = pmap.valueAt(ip); 13499 final int N = uids.size(); 13500 for (int i=0; i<N; i++) { 13501 int puid = uids.keyAt(i); 13502 ProcessRecord r = mProcessNames.get(pname, puid); 13503 if (dumpPackage != null && (r == null 13504 || !r.pkgList.containsKey(dumpPackage))) { 13505 continue; 13506 } 13507 if (!printed) { 13508 if (needSep) pw.println(); 13509 needSep = true; 13510 pw.println(" Bad processes:"); 13511 printedAnything = true; 13512 } 13513 BadProcessInfo info = uids.valueAt(i); 13514 pw.print(" Bad process "); pw.print(pname); 13515 pw.print(" uid "); pw.print(puid); 13516 pw.print(": crashed at time "); pw.println(info.time); 13517 if (info.shortMsg != null) { 13518 pw.print(" Short msg: "); pw.println(info.shortMsg); 13519 } 13520 if (info.longMsg != null) { 13521 pw.print(" Long msg: "); pw.println(info.longMsg); 13522 } 13523 if (info.stack != null) { 13524 pw.println(" Stack:"); 13525 int lastPos = 0; 13526 for (int pos=0; pos<info.stack.length(); pos++) { 13527 if (info.stack.charAt(pos) == '\n') { 13528 pw.print(" "); 13529 pw.write(info.stack, lastPos, pos-lastPos); 13530 pw.println(); 13531 lastPos = pos+1; 13532 } 13533 } 13534 if (lastPos < info.stack.length()) { 13535 pw.print(" "); 13536 pw.write(info.stack, lastPos, info.stack.length()-lastPos); 13537 pw.println(); 13538 } 13539 } 13540 } 13541 } 13542 } 13543 13544 if (dumpPackage == null) { 13545 pw.println(); 13546 needSep = false; 13547 pw.println(" mStartedUsers:"); 13548 for (int i=0; i<mStartedUsers.size(); i++) { 13549 UserState uss = mStartedUsers.valueAt(i); 13550 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier()); 13551 pw.print(": "); uss.dump("", pw); 13552 } 13553 pw.print(" mStartedUserArray: ["); 13554 for (int i=0; i<mStartedUserArray.length; i++) { 13555 if (i > 0) pw.print(", "); 13556 pw.print(mStartedUserArray[i]); 13557 } 13558 pw.println("]"); 13559 pw.print(" mUserLru: ["); 13560 for (int i=0; i<mUserLru.size(); i++) { 13561 if (i > 0) pw.print(", "); 13562 pw.print(mUserLru.get(i)); 13563 } 13564 pw.println("]"); 13565 if (dumpAll) { 13566 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray)); 13567 } 13568 synchronized (mUserProfileGroupIdsSelfLocked) { 13569 if (mUserProfileGroupIdsSelfLocked.size() > 0) { 13570 pw.println(" mUserProfileGroupIds:"); 13571 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) { 13572 pw.print(" User #"); 13573 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i)); 13574 pw.print(" -> profile #"); 13575 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i)); 13576 } 13577 } 13578 } 13579 } 13580 if (mHomeProcess != null && (dumpPackage == null 13581 || mHomeProcess.pkgList.containsKey(dumpPackage))) { 13582 if (needSep) { 13583 pw.println(); 13584 needSep = false; 13585 } 13586 pw.println(" mHomeProcess: " + mHomeProcess); 13587 } 13588 if (mPreviousProcess != null && (dumpPackage == null 13589 || mPreviousProcess.pkgList.containsKey(dumpPackage))) { 13590 if (needSep) { 13591 pw.println(); 13592 needSep = false; 13593 } 13594 pw.println(" mPreviousProcess: " + mPreviousProcess); 13595 } 13596 if (dumpAll) { 13597 StringBuilder sb = new StringBuilder(128); 13598 sb.append(" mPreviousProcessVisibleTime: "); 13599 TimeUtils.formatDuration(mPreviousProcessVisibleTime, sb); 13600 pw.println(sb); 13601 } 13602 if (mHeavyWeightProcess != null && (dumpPackage == null 13603 || mHeavyWeightProcess.pkgList.containsKey(dumpPackage))) { 13604 if (needSep) { 13605 pw.println(); 13606 needSep = false; 13607 } 13608 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess); 13609 } 13610 if (dumpPackage == null) { 13611 pw.println(" mConfiguration: " + mConfiguration); 13612 } 13613 if (dumpAll) { 13614 pw.println(" mConfigWillChange: " + getFocusedStack().mConfigWillChange); 13615 if (mCompatModePackages.getPackages().size() > 0) { 13616 boolean printed = false; 13617 for (Map.Entry<String, Integer> entry 13618 : mCompatModePackages.getPackages().entrySet()) { 13619 String pkg = entry.getKey(); 13620 int mode = entry.getValue(); 13621 if (dumpPackage != null && !dumpPackage.equals(pkg)) { 13622 continue; 13623 } 13624 if (!printed) { 13625 pw.println(" mScreenCompatPackages:"); 13626 printed = true; 13627 } 13628 pw.print(" "); pw.print(pkg); pw.print(": "); 13629 pw.print(mode); pw.println(); 13630 } 13631 } 13632 } 13633 if (dumpPackage == null) { 13634 pw.println(" mWakefulness=" 13635 + PowerManagerInternal.wakefulnessToString(mWakefulness)); 13636 pw.println(" mSleepTokens=" + mSleepTokens); 13637 pw.println(" mSleeping=" + mSleeping + " mLockScreenShown=" 13638 + lockScreenShownToString()); 13639 pw.println(" mShuttingDown=" + mShuttingDown + " mTestPssMode=" + mTestPssMode); 13640 if (mRunningVoice != null) { 13641 pw.println(" mRunningVoice=" + mRunningVoice); 13642 pw.println(" mVoiceWakeLock" + mVoiceWakeLock); 13643 } 13644 } 13645 if (mDebugApp != null || mOrigDebugApp != null || mDebugTransient 13646 || mOrigWaitForDebugger) { 13647 if (dumpPackage == null || dumpPackage.equals(mDebugApp) 13648 || dumpPackage.equals(mOrigDebugApp)) { 13649 if (needSep) { 13650 pw.println(); 13651 needSep = false; 13652 } 13653 pw.println(" mDebugApp=" + mDebugApp + "/orig=" + mOrigDebugApp 13654 + " mDebugTransient=" + mDebugTransient 13655 + " mOrigWaitForDebugger=" + mOrigWaitForDebugger); 13656 } 13657 } 13658 if (mCurAppTimeTracker != null) { 13659 mCurAppTimeTracker.dumpWithHeader(pw, " ", true); 13660 } 13661 if (mMemWatchProcesses.getMap().size() > 0) { 13662 pw.println(" Mem watch processes:"); 13663 final ArrayMap<String, SparseArray<Pair<Long, String>>> procs 13664 = mMemWatchProcesses.getMap(); 13665 for (int i=0; i<procs.size(); i++) { 13666 final String proc = procs.keyAt(i); 13667 final SparseArray<Pair<Long, String>> uids = procs.valueAt(i); 13668 for (int j=0; j<uids.size(); j++) { 13669 if (needSep) { 13670 pw.println(); 13671 needSep = false; 13672 } 13673 StringBuilder sb = new StringBuilder(); 13674 sb.append(" ").append(proc).append('/'); 13675 UserHandle.formatUid(sb, uids.keyAt(j)); 13676 Pair<Long, String> val = uids.valueAt(j); 13677 sb.append(": "); DebugUtils.sizeValueToString(val.first, sb); 13678 if (val.second != null) { 13679 sb.append(", report to ").append(val.second); 13680 } 13681 pw.println(sb.toString()); 13682 } 13683 } 13684 pw.print(" mMemWatchDumpProcName="); pw.println(mMemWatchDumpProcName); 13685 pw.print(" mMemWatchDumpFile="); pw.println(mMemWatchDumpFile); 13686 pw.print(" mMemWatchDumpPid="); pw.print(mMemWatchDumpPid); 13687 pw.print(" mMemWatchDumpUid="); pw.println(mMemWatchDumpUid); 13688 } 13689 if (mOpenGlTraceApp != null) { 13690 if (dumpPackage == null || dumpPackage.equals(mOpenGlTraceApp)) { 13691 if (needSep) { 13692 pw.println(); 13693 needSep = false; 13694 } 13695 pw.println(" mOpenGlTraceApp=" + mOpenGlTraceApp); 13696 } 13697 } 13698 if (mProfileApp != null || mProfileProc != null || mProfileFile != null 13699 || mProfileFd != null) { 13700 if (dumpPackage == null || dumpPackage.equals(mProfileApp)) { 13701 if (needSep) { 13702 pw.println(); 13703 needSep = false; 13704 } 13705 pw.println(" mProfileApp=" + mProfileApp + " mProfileProc=" + mProfileProc); 13706 pw.println(" mProfileFile=" + mProfileFile + " mProfileFd=" + mProfileFd); 13707 pw.println(" mSamplingInterval=" + mSamplingInterval + " mAutoStopProfiler=" 13708 + mAutoStopProfiler); 13709 pw.println(" mProfileType=" + mProfileType); 13710 } 13711 } 13712 if (dumpPackage == null) { 13713 if (mAlwaysFinishActivities || mController != null) { 13714 pw.println(" mAlwaysFinishActivities=" + mAlwaysFinishActivities 13715 + " mController=" + mController); 13716 } 13717 if (dumpAll) { 13718 pw.println(" Total persistent processes: " + numPers); 13719 pw.println(" mProcessesReady=" + mProcessesReady 13720 + " mSystemReady=" + mSystemReady 13721 + " mBooted=" + mBooted 13722 + " mFactoryTest=" + mFactoryTest); 13723 pw.println(" mBooting=" + mBooting 13724 + " mCallFinishBooting=" + mCallFinishBooting 13725 + " mBootAnimationComplete=" + mBootAnimationComplete); 13726 pw.print(" mLastPowerCheckRealtime="); 13727 TimeUtils.formatDuration(mLastPowerCheckRealtime, pw); 13728 pw.println(""); 13729 pw.print(" mLastPowerCheckUptime="); 13730 TimeUtils.formatDuration(mLastPowerCheckUptime, pw); 13731 pw.println(""); 13732 pw.println(" mGoingToSleep=" + mStackSupervisor.mGoingToSleep); 13733 pw.println(" mLaunchingActivity=" + mStackSupervisor.mLaunchingActivity); 13734 pw.println(" mAdjSeq=" + mAdjSeq + " mLruSeq=" + mLruSeq); 13735 pw.println(" mNumNonCachedProcs=" + mNumNonCachedProcs 13736 + " (" + mLruProcesses.size() + " total)" 13737 + " mNumCachedHiddenProcs=" + mNumCachedHiddenProcs 13738 + " mNumServiceProcs=" + mNumServiceProcs 13739 + " mNewNumServiceProcs=" + mNewNumServiceProcs); 13740 pw.println(" mAllowLowerMemLevel=" + mAllowLowerMemLevel 13741 + " mLastMemoryLevel" + mLastMemoryLevel 13742 + " mLastNumProcesses" + mLastNumProcesses); 13743 long now = SystemClock.uptimeMillis(); 13744 pw.print(" mLastIdleTime="); 13745 TimeUtils.formatDuration(now, mLastIdleTime, pw); 13746 pw.print(" mLowRamSinceLastIdle="); 13747 TimeUtils.formatDuration(getLowRamTimeSinceIdle(now), pw); 13748 pw.println(); 13749 } 13750 } 13751 13752 if (!printedAnything) { 13753 pw.println(" (nothing)"); 13754 } 13755 } 13756 dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean needSep, boolean dumpAll, String dumpPackage)13757 boolean dumpProcessesToGc(FileDescriptor fd, PrintWriter pw, String[] args, 13758 int opti, boolean needSep, boolean dumpAll, String dumpPackage) { 13759 if (mProcessesToGc.size() > 0) { 13760 boolean printed = false; 13761 long now = SystemClock.uptimeMillis(); 13762 for (int i=0; i<mProcessesToGc.size(); i++) { 13763 ProcessRecord proc = mProcessesToGc.get(i); 13764 if (dumpPackage != null && !dumpPackage.equals(proc.info.packageName)) { 13765 continue; 13766 } 13767 if (!printed) { 13768 if (needSep) pw.println(); 13769 needSep = true; 13770 pw.println(" Processes that are waiting to GC:"); 13771 printed = true; 13772 } 13773 pw.print(" Process "); pw.println(proc); 13774 pw.print(" lowMem="); pw.print(proc.reportLowMemory); 13775 pw.print(", last gced="); 13776 pw.print(now-proc.lastRequestedGc); 13777 pw.print(" ms ago, last lowMem="); 13778 pw.print(now-proc.lastLowMemory); 13779 pw.println(" ms ago"); 13780 13781 } 13782 } 13783 return needSep; 13784 } 13785 printOomLevel(PrintWriter pw, String name, int adj)13786 void printOomLevel(PrintWriter pw, String name, int adj) { 13787 pw.print(" "); 13788 if (adj >= 0) { 13789 pw.print(' '); 13790 if (adj < 10) pw.print(' '); 13791 } else { 13792 if (adj > -10) pw.print(' '); 13793 } 13794 pw.print(adj); 13795 pw.print(": "); 13796 pw.print(name); 13797 pw.print(" ("); 13798 pw.print(mProcessList.getMemLevel(adj)/1024); 13799 pw.println(" kB)"); 13800 } 13801 dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll)13802 boolean dumpOomLocked(FileDescriptor fd, PrintWriter pw, String[] args, 13803 int opti, boolean dumpAll) { 13804 boolean needSep = false; 13805 13806 if (mLruProcesses.size() > 0) { 13807 if (needSep) pw.println(); 13808 needSep = true; 13809 pw.println(" OOM levels:"); 13810 printOomLevel(pw, "SYSTEM_ADJ", ProcessList.SYSTEM_ADJ); 13811 printOomLevel(pw, "PERSISTENT_PROC_ADJ", ProcessList.PERSISTENT_PROC_ADJ); 13812 printOomLevel(pw, "PERSISTENT_SERVICE_ADJ", ProcessList.PERSISTENT_SERVICE_ADJ); 13813 printOomLevel(pw, "FOREGROUND_APP_ADJ", ProcessList.FOREGROUND_APP_ADJ); 13814 printOomLevel(pw, "VISIBLE_APP_ADJ", ProcessList.VISIBLE_APP_ADJ); 13815 printOomLevel(pw, "PERCEPTIBLE_APP_ADJ", ProcessList.PERCEPTIBLE_APP_ADJ); 13816 printOomLevel(pw, "BACKUP_APP_ADJ", ProcessList.BACKUP_APP_ADJ); 13817 printOomLevel(pw, "HEAVY_WEIGHT_APP_ADJ", ProcessList.HEAVY_WEIGHT_APP_ADJ); 13818 printOomLevel(pw, "SERVICE_ADJ", ProcessList.SERVICE_ADJ); 13819 printOomLevel(pw, "HOME_APP_ADJ", ProcessList.HOME_APP_ADJ); 13820 printOomLevel(pw, "PREVIOUS_APP_ADJ", ProcessList.PREVIOUS_APP_ADJ); 13821 printOomLevel(pw, "SERVICE_B_ADJ", ProcessList.SERVICE_B_ADJ); 13822 printOomLevel(pw, "CACHED_APP_MIN_ADJ", ProcessList.CACHED_APP_MIN_ADJ); 13823 printOomLevel(pw, "CACHED_APP_MAX_ADJ", ProcessList.CACHED_APP_MAX_ADJ); 13824 13825 if (needSep) pw.println(); 13826 pw.print(" Process OOM control ("); pw.print(mLruProcesses.size()); 13827 pw.print(" total, non-act at "); 13828 pw.print(mLruProcesses.size()-mLruProcessActivityStart); 13829 pw.print(", non-svc at "); 13830 pw.print(mLruProcesses.size()-mLruProcessServiceStart); 13831 pw.println("):"); 13832 dumpProcessOomList(pw, this, mLruProcesses, " ", "Proc", "PERS", true, null); 13833 needSep = true; 13834 } 13835 13836 dumpProcessesToGc(fd, pw, args, opti, needSep, dumpAll, null); 13837 13838 pw.println(); 13839 pw.println(" mHomeProcess: " + mHomeProcess); 13840 pw.println(" mPreviousProcess: " + mPreviousProcess); 13841 if (mHeavyWeightProcess != null) { 13842 pw.println(" mHeavyWeightProcess: " + mHeavyWeightProcess); 13843 } 13844 13845 return true; 13846 } 13847 13848 /** 13849 * There are three ways to call this: 13850 * - no provider specified: dump all the providers 13851 * - a flattened component name that matched an existing provider was specified as the 13852 * first arg: dump that one provider 13853 * - the first arg isn't the flattened component name of an existing provider: 13854 * dump all providers whose component contains the first arg as a substring 13855 */ dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll)13856 protected boolean dumpProvider(FileDescriptor fd, PrintWriter pw, String name, String[] args, 13857 int opti, boolean dumpAll) { 13858 return mProviderMap.dumpProvider(fd, pw, name, args, opti, dumpAll); 13859 } 13860 13861 static class ItemMatcher { 13862 ArrayList<ComponentName> components; 13863 ArrayList<String> strings; 13864 ArrayList<Integer> objects; 13865 boolean all; 13866 ItemMatcher()13867 ItemMatcher() { 13868 all = true; 13869 } 13870 build(String name)13871 void build(String name) { 13872 ComponentName componentName = ComponentName.unflattenFromString(name); 13873 if (componentName != null) { 13874 if (components == null) { 13875 components = new ArrayList<ComponentName>(); 13876 } 13877 components.add(componentName); 13878 all = false; 13879 } else { 13880 int objectId = 0; 13881 // Not a '/' separated full component name; maybe an object ID? 13882 try { 13883 objectId = Integer.parseInt(name, 16); 13884 if (objects == null) { 13885 objects = new ArrayList<Integer>(); 13886 } 13887 objects.add(objectId); 13888 all = false; 13889 } catch (RuntimeException e) { 13890 // Not an integer; just do string match. 13891 if (strings == null) { 13892 strings = new ArrayList<String>(); 13893 } 13894 strings.add(name); 13895 all = false; 13896 } 13897 } 13898 } 13899 build(String[] args, int opti)13900 int build(String[] args, int opti) { 13901 for (; opti<args.length; opti++) { 13902 String name = args[opti]; 13903 if ("--".equals(name)) { 13904 return opti+1; 13905 } 13906 build(name); 13907 } 13908 return opti; 13909 } 13910 match(Object object, ComponentName comp)13911 boolean match(Object object, ComponentName comp) { 13912 if (all) { 13913 return true; 13914 } 13915 if (components != null) { 13916 for (int i=0; i<components.size(); i++) { 13917 if (components.get(i).equals(comp)) { 13918 return true; 13919 } 13920 } 13921 } 13922 if (objects != null) { 13923 for (int i=0; i<objects.size(); i++) { 13924 if (System.identityHashCode(object) == objects.get(i)) { 13925 return true; 13926 } 13927 } 13928 } 13929 if (strings != null) { 13930 String flat = comp.flattenToString(); 13931 for (int i=0; i<strings.size(); i++) { 13932 if (flat.contains(strings.get(i))) { 13933 return true; 13934 } 13935 } 13936 } 13937 return false; 13938 } 13939 } 13940 13941 /** 13942 * There are three things that cmd can be: 13943 * - a flattened component name that matches an existing activity 13944 * - the cmd arg isn't the flattened component name of an existing activity: 13945 * dump all activity whose component contains the cmd as a substring 13946 * - A hex number of the ActivityRecord object instance. 13947 */ dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, int opti, boolean dumpAll)13948 protected boolean dumpActivity(FileDescriptor fd, PrintWriter pw, String name, String[] args, 13949 int opti, boolean dumpAll) { 13950 ArrayList<ActivityRecord> activities; 13951 13952 synchronized (this) { 13953 activities = mStackSupervisor.getDumpActivitiesLocked(name); 13954 } 13955 13956 if (activities.size() <= 0) { 13957 return false; 13958 } 13959 13960 String[] newArgs = new String[args.length - opti]; 13961 System.arraycopy(args, opti, newArgs, 0, args.length - opti); 13962 13963 TaskRecord lastTask = null; 13964 boolean needSep = false; 13965 for (int i=activities.size()-1; i>=0; i--) { 13966 ActivityRecord r = activities.get(i); 13967 if (needSep) { 13968 pw.println(); 13969 } 13970 needSep = true; 13971 synchronized (this) { 13972 if (lastTask != r.task) { 13973 lastTask = r.task; 13974 pw.print("TASK "); pw.print(lastTask.affinity); 13975 pw.print(" id="); pw.println(lastTask.taskId); 13976 if (dumpAll) { 13977 lastTask.dump(pw, " "); 13978 } 13979 } 13980 } 13981 dumpActivity(" ", fd, pw, activities.get(i), newArgs, dumpAll); 13982 } 13983 return true; 13984 } 13985 13986 /** 13987 * Invokes IApplicationThread.dumpActivity() on the thread of the specified activity if 13988 * there is a thread associated with the activity. 13989 */ dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw, final ActivityRecord r, String[] args, boolean dumpAll)13990 private void dumpActivity(String prefix, FileDescriptor fd, PrintWriter pw, 13991 final ActivityRecord r, String[] args, boolean dumpAll) { 13992 String innerPrefix = prefix + " "; 13993 synchronized (this) { 13994 pw.print(prefix); pw.print("ACTIVITY "); pw.print(r.shortComponentName); 13995 pw.print(" "); pw.print(Integer.toHexString(System.identityHashCode(r))); 13996 pw.print(" pid="); 13997 if (r.app != null) pw.println(r.app.pid); 13998 else pw.println("(not running)"); 13999 if (dumpAll) { 14000 r.dump(pw, innerPrefix); 14001 } 14002 } 14003 if (r.app != null && r.app.thread != null) { 14004 // flush anything that is already in the PrintWriter since the thread is going 14005 // to write to the file descriptor directly 14006 pw.flush(); 14007 try { 14008 TransferPipe tp = new TransferPipe(); 14009 try { 14010 r.app.thread.dumpActivity(tp.getWriteFd().getFileDescriptor(), 14011 r.appToken, innerPrefix, args); 14012 tp.go(fd); 14013 } finally { 14014 tp.kill(); 14015 } 14016 } catch (IOException e) { 14017 pw.println(innerPrefix + "Failure while dumping the activity: " + e); 14018 } catch (RemoteException e) { 14019 pw.println(innerPrefix + "Got a RemoteException while dumping the activity"); 14020 } 14021 } 14022 } 14023 dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)14024 void dumpBroadcastsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 14025 int opti, boolean dumpAll, String dumpPackage) { 14026 boolean needSep = false; 14027 boolean onlyHistory = false; 14028 boolean printedAnything = false; 14029 14030 if ("history".equals(dumpPackage)) { 14031 if (opti < args.length && "-s".equals(args[opti])) { 14032 dumpAll = false; 14033 } 14034 onlyHistory = true; 14035 dumpPackage = null; 14036 } 14037 14038 pw.println("ACTIVITY MANAGER BROADCAST STATE (dumpsys activity broadcasts)"); 14039 if (!onlyHistory && dumpAll) { 14040 if (mRegisteredReceivers.size() > 0) { 14041 boolean printed = false; 14042 Iterator it = mRegisteredReceivers.values().iterator(); 14043 while (it.hasNext()) { 14044 ReceiverList r = (ReceiverList)it.next(); 14045 if (dumpPackage != null && (r.app == null || 14046 !dumpPackage.equals(r.app.info.packageName))) { 14047 continue; 14048 } 14049 if (!printed) { 14050 pw.println(" Registered Receivers:"); 14051 needSep = true; 14052 printed = true; 14053 printedAnything = true; 14054 } 14055 pw.print(" * "); pw.println(r); 14056 r.dump(pw, " "); 14057 } 14058 } 14059 14060 if (mReceiverResolver.dump(pw, needSep ? 14061 "\n Receiver Resolver Table:" : " Receiver Resolver Table:", 14062 " ", dumpPackage, false, false)) { 14063 needSep = true; 14064 printedAnything = true; 14065 } 14066 } 14067 14068 for (BroadcastQueue q : mBroadcastQueues) { 14069 needSep = q.dumpLocked(fd, pw, args, opti, dumpAll, dumpPackage, needSep); 14070 printedAnything |= needSep; 14071 } 14072 14073 needSep = true; 14074 14075 if (!onlyHistory && mStickyBroadcasts != null && dumpPackage == null) { 14076 for (int user=0; user<mStickyBroadcasts.size(); user++) { 14077 if (needSep) { 14078 pw.println(); 14079 } 14080 needSep = true; 14081 printedAnything = true; 14082 pw.print(" Sticky broadcasts for user "); 14083 pw.print(mStickyBroadcasts.keyAt(user)); pw.println(":"); 14084 StringBuilder sb = new StringBuilder(128); 14085 for (Map.Entry<String, ArrayList<Intent>> ent 14086 : mStickyBroadcasts.valueAt(user).entrySet()) { 14087 pw.print(" * Sticky action "); pw.print(ent.getKey()); 14088 if (dumpAll) { 14089 pw.println(":"); 14090 ArrayList<Intent> intents = ent.getValue(); 14091 final int N = intents.size(); 14092 for (int i=0; i<N; i++) { 14093 sb.setLength(0); 14094 sb.append(" Intent: "); 14095 intents.get(i).toShortString(sb, false, true, false, false); 14096 pw.println(sb.toString()); 14097 Bundle bundle = intents.get(i).getExtras(); 14098 if (bundle != null) { 14099 pw.print(" "); 14100 pw.println(bundle.toString()); 14101 } 14102 } 14103 } else { 14104 pw.println(""); 14105 } 14106 } 14107 } 14108 } 14109 14110 if (!onlyHistory && dumpAll) { 14111 pw.println(); 14112 for (BroadcastQueue queue : mBroadcastQueues) { 14113 pw.println(" mBroadcastsScheduled [" + queue.mQueueName + "]=" 14114 + queue.mBroadcastsScheduled); 14115 } 14116 pw.println(" mHandler:"); 14117 mHandler.dump(new PrintWriterPrinter(pw), " "); 14118 needSep = true; 14119 printedAnything = true; 14120 } 14121 14122 if (!printedAnything) { 14123 pw.println(" (nothing)"); 14124 } 14125 } 14126 dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)14127 void dumpProvidersLocked(FileDescriptor fd, PrintWriter pw, String[] args, 14128 int opti, boolean dumpAll, String dumpPackage) { 14129 boolean needSep; 14130 boolean printedAnything = false; 14131 14132 ItemMatcher matcher = new ItemMatcher(); 14133 matcher.build(args, opti); 14134 14135 pw.println("ACTIVITY MANAGER CONTENT PROVIDERS (dumpsys activity providers)"); 14136 14137 needSep = mProviderMap.dumpProvidersLocked(pw, dumpAll, dumpPackage); 14138 printedAnything |= needSep; 14139 14140 if (mLaunchingProviders.size() > 0) { 14141 boolean printed = false; 14142 for (int i=mLaunchingProviders.size()-1; i>=0; i--) { 14143 ContentProviderRecord r = mLaunchingProviders.get(i); 14144 if (dumpPackage != null && !dumpPackage.equals(r.name.getPackageName())) { 14145 continue; 14146 } 14147 if (!printed) { 14148 if (needSep) pw.println(); 14149 needSep = true; 14150 pw.println(" Launching content providers:"); 14151 printed = true; 14152 printedAnything = true; 14153 } 14154 pw.print(" Launching #"); pw.print(i); pw.print(": "); 14155 pw.println(r); 14156 } 14157 } 14158 14159 if (!printedAnything) { 14160 pw.println(" (nothing)"); 14161 } 14162 } 14163 dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)14164 void dumpPermissionsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 14165 int opti, boolean dumpAll, String dumpPackage) { 14166 boolean needSep = false; 14167 boolean printedAnything = false; 14168 14169 pw.println("ACTIVITY MANAGER URI PERMISSIONS (dumpsys activity permissions)"); 14170 14171 if (mGrantedUriPermissions.size() > 0) { 14172 boolean printed = false; 14173 int dumpUid = -2; 14174 if (dumpPackage != null) { 14175 try { 14176 dumpUid = mContext.getPackageManager().getPackageUid(dumpPackage, 0); 14177 } catch (NameNotFoundException e) { 14178 dumpUid = -1; 14179 } 14180 } 14181 for (int i=0; i<mGrantedUriPermissions.size(); i++) { 14182 int uid = mGrantedUriPermissions.keyAt(i); 14183 if (dumpUid >= -1 && UserHandle.getAppId(uid) != dumpUid) { 14184 continue; 14185 } 14186 final ArrayMap<GrantUri, UriPermission> perms = mGrantedUriPermissions.valueAt(i); 14187 if (!printed) { 14188 if (needSep) pw.println(); 14189 needSep = true; 14190 pw.println(" Granted Uri Permissions:"); 14191 printed = true; 14192 printedAnything = true; 14193 } 14194 pw.print(" * UID "); pw.print(uid); pw.println(" holds:"); 14195 for (UriPermission perm : perms.values()) { 14196 pw.print(" "); pw.println(perm); 14197 if (dumpAll) { 14198 perm.dump(pw, " "); 14199 } 14200 } 14201 } 14202 } 14203 14204 if (!printedAnything) { 14205 pw.println(" (nothing)"); 14206 } 14207 } 14208 dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, int opti, boolean dumpAll, String dumpPackage)14209 void dumpPendingIntentsLocked(FileDescriptor fd, PrintWriter pw, String[] args, 14210 int opti, boolean dumpAll, String dumpPackage) { 14211 boolean printed = false; 14212 14213 pw.println("ACTIVITY MANAGER PENDING INTENTS (dumpsys activity intents)"); 14214 14215 if (mIntentSenderRecords.size() > 0) { 14216 Iterator<WeakReference<PendingIntentRecord>> it 14217 = mIntentSenderRecords.values().iterator(); 14218 while (it.hasNext()) { 14219 WeakReference<PendingIntentRecord> ref = it.next(); 14220 PendingIntentRecord rec = ref != null ? ref.get(): null; 14221 if (dumpPackage != null && (rec == null 14222 || !dumpPackage.equals(rec.key.packageName))) { 14223 continue; 14224 } 14225 printed = true; 14226 if (rec != null) { 14227 pw.print(" * "); pw.println(rec); 14228 if (dumpAll) { 14229 rec.dump(pw, " "); 14230 } 14231 } else { 14232 pw.print(" * "); pw.println(ref); 14233 } 14234 } 14235 } 14236 14237 if (!printed) { 14238 pw.println(" (nothing)"); 14239 } 14240 } 14241 dumpProcessList(PrintWriter pw, ActivityManagerService service, List list, String prefix, String normalLabel, String persistentLabel, String dumpPackage)14242 private static final int dumpProcessList(PrintWriter pw, 14243 ActivityManagerService service, List list, 14244 String prefix, String normalLabel, String persistentLabel, 14245 String dumpPackage) { 14246 int numPers = 0; 14247 final int N = list.size()-1; 14248 for (int i=N; i>=0; i--) { 14249 ProcessRecord r = (ProcessRecord)list.get(i); 14250 if (dumpPackage != null && !dumpPackage.equals(r.info.packageName)) { 14251 continue; 14252 } 14253 pw.println(String.format("%s%s #%2d: %s", 14254 prefix, (r.persistent ? persistentLabel : normalLabel), 14255 i, r.toString())); 14256 if (r.persistent) { 14257 numPers++; 14258 } 14259 } 14260 return numPers; 14261 } 14262 dumpProcessOomList(PrintWriter pw, ActivityManagerService service, List<ProcessRecord> origList, String prefix, String normalLabel, String persistentLabel, boolean inclDetails, String dumpPackage)14263 private static final boolean dumpProcessOomList(PrintWriter pw, 14264 ActivityManagerService service, List<ProcessRecord> origList, 14265 String prefix, String normalLabel, String persistentLabel, 14266 boolean inclDetails, String dumpPackage) { 14267 14268 ArrayList<Pair<ProcessRecord, Integer>> list 14269 = new ArrayList<Pair<ProcessRecord, Integer>>(origList.size()); 14270 for (int i=0; i<origList.size(); i++) { 14271 ProcessRecord r = origList.get(i); 14272 if (dumpPackage != null && !r.pkgList.containsKey(dumpPackage)) { 14273 continue; 14274 } 14275 list.add(new Pair<ProcessRecord, Integer>(origList.get(i), i)); 14276 } 14277 14278 if (list.size() <= 0) { 14279 return false; 14280 } 14281 14282 Comparator<Pair<ProcessRecord, Integer>> comparator 14283 = new Comparator<Pair<ProcessRecord, Integer>>() { 14284 @Override 14285 public int compare(Pair<ProcessRecord, Integer> object1, 14286 Pair<ProcessRecord, Integer> object2) { 14287 if (object1.first.setAdj != object2.first.setAdj) { 14288 return object1.first.setAdj > object2.first.setAdj ? -1 : 1; 14289 } 14290 if (object1.second.intValue() != object2.second.intValue()) { 14291 return object1.second.intValue() > object2.second.intValue() ? -1 : 1; 14292 } 14293 return 0; 14294 } 14295 }; 14296 14297 Collections.sort(list, comparator); 14298 14299 final long curRealtime = SystemClock.elapsedRealtime(); 14300 final long realtimeSince = curRealtime - service.mLastPowerCheckRealtime; 14301 final long curUptime = SystemClock.uptimeMillis(); 14302 final long uptimeSince = curUptime - service.mLastPowerCheckUptime; 14303 14304 for (int i=list.size()-1; i>=0; i--) { 14305 ProcessRecord r = list.get(i).first; 14306 String oomAdj = ProcessList.makeOomAdjString(r.setAdj); 14307 char schedGroup; 14308 switch (r.setSchedGroup) { 14309 case Process.THREAD_GROUP_BG_NONINTERACTIVE: 14310 schedGroup = 'B'; 14311 break; 14312 case Process.THREAD_GROUP_DEFAULT: 14313 schedGroup = 'F'; 14314 break; 14315 default: 14316 schedGroup = '?'; 14317 break; 14318 } 14319 char foreground; 14320 if (r.foregroundActivities) { 14321 foreground = 'A'; 14322 } else if (r.foregroundServices) { 14323 foreground = 'S'; 14324 } else { 14325 foreground = ' '; 14326 } 14327 String procState = ProcessList.makeProcStateString(r.curProcState); 14328 pw.print(prefix); 14329 pw.print(r.persistent ? persistentLabel : normalLabel); 14330 pw.print(" #"); 14331 int num = (origList.size()-1)-list.get(i).second; 14332 if (num < 10) pw.print(' '); 14333 pw.print(num); 14334 pw.print(": "); 14335 pw.print(oomAdj); 14336 pw.print(' '); 14337 pw.print(schedGroup); 14338 pw.print('/'); 14339 pw.print(foreground); 14340 pw.print('/'); 14341 pw.print(procState); 14342 pw.print(" trm:"); 14343 if (r.trimMemoryLevel < 10) pw.print(' '); 14344 pw.print(r.trimMemoryLevel); 14345 pw.print(' '); 14346 pw.print(r.toShortString()); 14347 pw.print(" ("); 14348 pw.print(r.adjType); 14349 pw.println(')'); 14350 if (r.adjSource != null || r.adjTarget != null) { 14351 pw.print(prefix); 14352 pw.print(" "); 14353 if (r.adjTarget instanceof ComponentName) { 14354 pw.print(((ComponentName)r.adjTarget).flattenToShortString()); 14355 } else if (r.adjTarget != null) { 14356 pw.print(r.adjTarget.toString()); 14357 } else { 14358 pw.print("{null}"); 14359 } 14360 pw.print("<="); 14361 if (r.adjSource instanceof ProcessRecord) { 14362 pw.print("Proc{"); 14363 pw.print(((ProcessRecord)r.adjSource).toShortString()); 14364 pw.println("}"); 14365 } else if (r.adjSource != null) { 14366 pw.println(r.adjSource.toString()); 14367 } else { 14368 pw.println("{null}"); 14369 } 14370 } 14371 if (inclDetails) { 14372 pw.print(prefix); 14373 pw.print(" "); 14374 pw.print("oom: max="); pw.print(r.maxAdj); 14375 pw.print(" curRaw="); pw.print(r.curRawAdj); 14376 pw.print(" setRaw="); pw.print(r.setRawAdj); 14377 pw.print(" cur="); pw.print(r.curAdj); 14378 pw.print(" set="); pw.println(r.setAdj); 14379 pw.print(prefix); 14380 pw.print(" "); 14381 pw.print("state: cur="); pw.print(ProcessList.makeProcStateString(r.curProcState)); 14382 pw.print(" set="); pw.print(ProcessList.makeProcStateString(r.setProcState)); 14383 pw.print(" lastPss="); DebugUtils.printSizeValue(pw, r.lastPss*1024); 14384 pw.print(" lastCachedPss="); DebugUtils.printSizeValue(pw, r.lastCachedPss*1024); 14385 pw.println(); 14386 pw.print(prefix); 14387 pw.print(" "); 14388 pw.print("cached="); pw.print(r.cached); 14389 pw.print(" empty="); pw.print(r.empty); 14390 pw.print(" hasAboveClient="); pw.println(r.hasAboveClient); 14391 14392 if (r.setProcState >= ActivityManager.PROCESS_STATE_SERVICE) { 14393 if (r.lastWakeTime != 0) { 14394 long wtime; 14395 BatteryStatsImpl stats = service.mBatteryStatsService.getActiveStatistics(); 14396 synchronized (stats) { 14397 wtime = stats.getProcessWakeTime(r.info.uid, 14398 r.pid, curRealtime); 14399 } 14400 long timeUsed = wtime - r.lastWakeTime; 14401 pw.print(prefix); 14402 pw.print(" "); 14403 pw.print("keep awake over "); 14404 TimeUtils.formatDuration(realtimeSince, pw); 14405 pw.print(" used "); 14406 TimeUtils.formatDuration(timeUsed, pw); 14407 pw.print(" ("); 14408 pw.print((timeUsed*100)/realtimeSince); 14409 pw.println("%)"); 14410 } 14411 if (r.lastCpuTime != 0) { 14412 long timeUsed = r.curCpuTime - r.lastCpuTime; 14413 pw.print(prefix); 14414 pw.print(" "); 14415 pw.print("run cpu over "); 14416 TimeUtils.formatDuration(uptimeSince, pw); 14417 pw.print(" used "); 14418 TimeUtils.formatDuration(timeUsed, pw); 14419 pw.print(" ("); 14420 pw.print((timeUsed*100)/uptimeSince); 14421 pw.println("%)"); 14422 } 14423 } 14424 } 14425 } 14426 return true; 14427 } 14428 collectProcesses(PrintWriter pw, int start, boolean allPkgs, String[] args)14429 ArrayList<ProcessRecord> collectProcesses(PrintWriter pw, int start, boolean allPkgs, 14430 String[] args) { 14431 ArrayList<ProcessRecord> procs; 14432 synchronized (this) { 14433 if (args != null && args.length > start 14434 && args[start].charAt(0) != '-') { 14435 procs = new ArrayList<ProcessRecord>(); 14436 int pid = -1; 14437 try { 14438 pid = Integer.parseInt(args[start]); 14439 } catch (NumberFormatException e) { 14440 } 14441 for (int i=mLruProcesses.size()-1; i>=0; i--) { 14442 ProcessRecord proc = mLruProcesses.get(i); 14443 if (proc.pid == pid) { 14444 procs.add(proc); 14445 } else if (allPkgs && proc.pkgList != null 14446 && proc.pkgList.containsKey(args[start])) { 14447 procs.add(proc); 14448 } else if (proc.processName.equals(args[start])) { 14449 procs.add(proc); 14450 } 14451 } 14452 if (procs.size() <= 0) { 14453 return null; 14454 } 14455 } else { 14456 procs = new ArrayList<ProcessRecord>(mLruProcesses); 14457 } 14458 } 14459 return procs; 14460 } 14461 dumpGraphicsHardwareUsage(FileDescriptor fd, PrintWriter pw, String[] args)14462 final void dumpGraphicsHardwareUsage(FileDescriptor fd, 14463 PrintWriter pw, String[] args) { 14464 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 14465 if (procs == null) { 14466 pw.println("No process found for: " + args[0]); 14467 return; 14468 } 14469 14470 long uptime = SystemClock.uptimeMillis(); 14471 long realtime = SystemClock.elapsedRealtime(); 14472 pw.println("Applications Graphics Acceleration Info:"); 14473 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 14474 14475 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 14476 ProcessRecord r = procs.get(i); 14477 if (r.thread != null) { 14478 pw.println("\n** Graphics info for pid " + r.pid + " [" + r.processName + "] **"); 14479 pw.flush(); 14480 try { 14481 TransferPipe tp = new TransferPipe(); 14482 try { 14483 r.thread.dumpGfxInfo(tp.getWriteFd().getFileDescriptor(), args); 14484 tp.go(fd); 14485 } finally { 14486 tp.kill(); 14487 } 14488 } catch (IOException e) { 14489 pw.println("Failure while dumping the app: " + r); 14490 pw.flush(); 14491 } catch (RemoteException e) { 14492 pw.println("Got a RemoteException while dumping the app " + r); 14493 pw.flush(); 14494 } 14495 } 14496 } 14497 } 14498 dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args)14499 final void dumpDbInfo(FileDescriptor fd, PrintWriter pw, String[] args) { 14500 ArrayList<ProcessRecord> procs = collectProcesses(pw, 0, false, args); 14501 if (procs == null) { 14502 pw.println("No process found for: " + args[0]); 14503 return; 14504 } 14505 14506 pw.println("Applications Database Info:"); 14507 14508 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 14509 ProcessRecord r = procs.get(i); 14510 if (r.thread != null) { 14511 pw.println("\n** Database info for pid " + r.pid + " [" + r.processName + "] **"); 14512 pw.flush(); 14513 try { 14514 TransferPipe tp = new TransferPipe(); 14515 try { 14516 r.thread.dumpDbInfo(tp.getWriteFd().getFileDescriptor(), args); 14517 tp.go(fd); 14518 } finally { 14519 tp.kill(); 14520 } 14521 } catch (IOException e) { 14522 pw.println("Failure while dumping the app: " + r); 14523 pw.flush(); 14524 } catch (RemoteException e) { 14525 pw.println("Got a RemoteException while dumping the app " + r); 14526 pw.flush(); 14527 } 14528 } 14529 } 14530 } 14531 14532 final static class MemItem { 14533 final boolean isProc; 14534 final String label; 14535 final String shortLabel; 14536 final long pss; 14537 final int id; 14538 final boolean hasActivities; 14539 ArrayList<MemItem> subitems; 14540 MemItem(String _label, String _shortLabel, long _pss, int _id, boolean _hasActivities)14541 public MemItem(String _label, String _shortLabel, long _pss, int _id, 14542 boolean _hasActivities) { 14543 isProc = true; 14544 label = _label; 14545 shortLabel = _shortLabel; 14546 pss = _pss; 14547 id = _id; 14548 hasActivities = _hasActivities; 14549 } 14550 MemItem(String _label, String _shortLabel, long _pss, int _id)14551 public MemItem(String _label, String _shortLabel, long _pss, int _id) { 14552 isProc = false; 14553 label = _label; 14554 shortLabel = _shortLabel; 14555 pss = _pss; 14556 id = _id; 14557 hasActivities = false; 14558 } 14559 } 14560 dumpMemItems(PrintWriter pw, String prefix, String tag, ArrayList<MemItem> items, boolean sort, boolean isCompact)14561 static final void dumpMemItems(PrintWriter pw, String prefix, String tag, 14562 ArrayList<MemItem> items, boolean sort, boolean isCompact) { 14563 if (sort && !isCompact) { 14564 Collections.sort(items, new Comparator<MemItem>() { 14565 @Override 14566 public int compare(MemItem lhs, MemItem rhs) { 14567 if (lhs.pss < rhs.pss) { 14568 return 1; 14569 } else if (lhs.pss > rhs.pss) { 14570 return -1; 14571 } 14572 return 0; 14573 } 14574 }); 14575 } 14576 14577 for (int i=0; i<items.size(); i++) { 14578 MemItem mi = items.get(i); 14579 if (!isCompact) { 14580 pw.print(prefix); pw.printf("%7d kB: ", mi.pss); pw.println(mi.label); 14581 } else if (mi.isProc) { 14582 pw.print("proc,"); pw.print(tag); pw.print(","); pw.print(mi.shortLabel); 14583 pw.print(","); pw.print(mi.id); pw.print(","); pw.print(mi.pss); 14584 pw.println(mi.hasActivities ? ",a" : ",e"); 14585 } else { 14586 pw.print(tag); pw.print(","); pw.print(mi.shortLabel); pw.print(","); 14587 pw.println(mi.pss); 14588 } 14589 if (mi.subitems != null) { 14590 dumpMemItems(pw, prefix + " ", mi.shortLabel, mi.subitems, 14591 true, isCompact); 14592 } 14593 } 14594 } 14595 14596 // These are in KB. 14597 static final long[] DUMP_MEM_BUCKETS = new long[] { 14598 5*1024, 7*1024, 10*1024, 15*1024, 20*1024, 30*1024, 40*1024, 80*1024, 14599 120*1024, 160*1024, 200*1024, 14600 250*1024, 300*1024, 350*1024, 400*1024, 500*1024, 600*1024, 800*1024, 14601 1*1024*1024, 2*1024*1024, 5*1024*1024, 10*1024*1024, 20*1024*1024 14602 }; 14603 appendMemBucket(StringBuilder out, long memKB, String label, boolean stackLike)14604 static final void appendMemBucket(StringBuilder out, long memKB, String label, 14605 boolean stackLike) { 14606 int start = label.lastIndexOf('.'); 14607 if (start >= 0) start++; 14608 else start = 0; 14609 int end = label.length(); 14610 for (int i=0; i<DUMP_MEM_BUCKETS.length; i++) { 14611 if (DUMP_MEM_BUCKETS[i] >= memKB) { 14612 long bucket = DUMP_MEM_BUCKETS[i]/1024; 14613 out.append(bucket); 14614 out.append(stackLike ? "MB." : "MB "); 14615 out.append(label, start, end); 14616 return; 14617 } 14618 } 14619 out.append(memKB/1024); 14620 out.append(stackLike ? "MB." : "MB "); 14621 out.append(label, start, end); 14622 } 14623 14624 static final int[] DUMP_MEM_OOM_ADJ = new int[] { 14625 ProcessList.NATIVE_ADJ, 14626 ProcessList.SYSTEM_ADJ, ProcessList.PERSISTENT_PROC_ADJ, 14627 ProcessList.PERSISTENT_SERVICE_ADJ, ProcessList.FOREGROUND_APP_ADJ, 14628 ProcessList.VISIBLE_APP_ADJ, ProcessList.PERCEPTIBLE_APP_ADJ, 14629 ProcessList.BACKUP_APP_ADJ, ProcessList.HEAVY_WEIGHT_APP_ADJ, 14630 ProcessList.SERVICE_ADJ, ProcessList.HOME_APP_ADJ, 14631 ProcessList.PREVIOUS_APP_ADJ, ProcessList.SERVICE_B_ADJ, ProcessList.CACHED_APP_MAX_ADJ 14632 }; 14633 static final String[] DUMP_MEM_OOM_LABEL = new String[] { 14634 "Native", 14635 "System", "Persistent", "Persistent Service", "Foreground", 14636 "Visible", "Perceptible", 14637 "Heavy Weight", "Backup", 14638 "A Services", "Home", 14639 "Previous", "B Services", "Cached" 14640 }; 14641 static final String[] DUMP_MEM_OOM_COMPACT_LABEL = new String[] { 14642 "native", 14643 "sys", "pers", "persvc", "fore", 14644 "vis", "percept", 14645 "heavy", "backup", 14646 "servicea", "home", 14647 "prev", "serviceb", "cached" 14648 }; 14649 dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, long realtime, boolean isCheckinRequest, boolean isCompact)14650 private final void dumpApplicationMemoryUsageHeader(PrintWriter pw, long uptime, 14651 long realtime, boolean isCheckinRequest, boolean isCompact) { 14652 if (isCheckinRequest || isCompact) { 14653 // short checkin version 14654 pw.print("time,"); pw.print(uptime); pw.print(","); pw.println(realtime); 14655 } else { 14656 pw.println("Applications Memory Usage (kB):"); 14657 pw.println("Uptime: " + uptime + " Realtime: " + realtime); 14658 } 14659 } 14660 14661 private static final int KSM_SHARED = 0; 14662 private static final int KSM_SHARING = 1; 14663 private static final int KSM_UNSHARED = 2; 14664 private static final int KSM_VOLATILE = 3; 14665 getKsmInfo()14666 private final long[] getKsmInfo() { 14667 long[] longOut = new long[4]; 14668 final int[] SINGLE_LONG_FORMAT = new int[] { 14669 Process.PROC_SPACE_TERM|Process.PROC_OUT_LONG 14670 }; 14671 long[] longTmp = new long[1]; 14672 Process.readProcFile("/sys/kernel/mm/ksm/pages_shared", 14673 SINGLE_LONG_FORMAT, null, longTmp, null); 14674 longOut[KSM_SHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 14675 longTmp[0] = 0; 14676 Process.readProcFile("/sys/kernel/mm/ksm/pages_sharing", 14677 SINGLE_LONG_FORMAT, null, longTmp, null); 14678 longOut[KSM_SHARING] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 14679 longTmp[0] = 0; 14680 Process.readProcFile("/sys/kernel/mm/ksm/pages_unshared", 14681 SINGLE_LONG_FORMAT, null, longTmp, null); 14682 longOut[KSM_UNSHARED] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 14683 longTmp[0] = 0; 14684 Process.readProcFile("/sys/kernel/mm/ksm/pages_volatile", 14685 SINGLE_LONG_FORMAT, null, longTmp, null); 14686 longOut[KSM_VOLATILE] = longTmp[0] * ProcessList.PAGE_SIZE / 1024; 14687 return longOut; 14688 } 14689 dumpApplicationMemoryUsage(FileDescriptor fd, PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw)14690 final void dumpApplicationMemoryUsage(FileDescriptor fd, 14691 PrintWriter pw, String prefix, String[] args, boolean brief, PrintWriter categoryPw) { 14692 boolean dumpDetails = false; 14693 boolean dumpFullDetails = false; 14694 boolean dumpDalvik = false; 14695 boolean dumpSummaryOnly = false; 14696 boolean oomOnly = false; 14697 boolean isCompact = false; 14698 boolean localOnly = false; 14699 boolean packages = false; 14700 14701 int opti = 0; 14702 while (opti < args.length) { 14703 String opt = args[opti]; 14704 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 14705 break; 14706 } 14707 opti++; 14708 if ("-a".equals(opt)) { 14709 dumpDetails = true; 14710 dumpFullDetails = true; 14711 dumpDalvik = true; 14712 } else if ("-d".equals(opt)) { 14713 dumpDalvik = true; 14714 } else if ("-c".equals(opt)) { 14715 isCompact = true; 14716 } else if ("-s".equals(opt)) { 14717 dumpDetails = true; 14718 dumpSummaryOnly = true; 14719 } else if ("--oom".equals(opt)) { 14720 oomOnly = true; 14721 } else if ("--local".equals(opt)) { 14722 localOnly = true; 14723 } else if ("--package".equals(opt)) { 14724 packages = true; 14725 } else if ("-h".equals(opt)) { 14726 pw.println("meminfo dump options: [-a] [-d] [-c] [-s] [--oom] [process]"); 14727 pw.println(" -a: include all available information for each process."); 14728 pw.println(" -d: include dalvik details."); 14729 pw.println(" -c: dump in a compact machine-parseable representation."); 14730 pw.println(" -s: dump only summary of application memory usage."); 14731 pw.println(" --oom: only show processes organized by oom adj."); 14732 pw.println(" --local: only collect details locally, don't call process."); 14733 pw.println(" --package: interpret process arg as package, dumping all"); 14734 pw.println(" processes that have loaded that package."); 14735 pw.println("If [process] is specified it can be the name or "); 14736 pw.println("pid of a specific process to dump."); 14737 return; 14738 } else { 14739 pw.println("Unknown argument: " + opt + "; use -h for help"); 14740 } 14741 } 14742 14743 final boolean isCheckinRequest = scanArgs(args, "--checkin"); 14744 long uptime = SystemClock.uptimeMillis(); 14745 long realtime = SystemClock.elapsedRealtime(); 14746 final long[] tmpLong = new long[1]; 14747 14748 ArrayList<ProcessRecord> procs = collectProcesses(pw, opti, packages, args); 14749 if (procs == null) { 14750 // No Java processes. Maybe they want to print a native process. 14751 if (args != null && args.length > opti 14752 && args[opti].charAt(0) != '-') { 14753 ArrayList<ProcessCpuTracker.Stats> nativeProcs 14754 = new ArrayList<ProcessCpuTracker.Stats>(); 14755 updateCpuStatsNow(); 14756 int findPid = -1; 14757 try { 14758 findPid = Integer.parseInt(args[opti]); 14759 } catch (NumberFormatException e) { 14760 } 14761 synchronized (mProcessCpuTracker) { 14762 final int N = mProcessCpuTracker.countStats(); 14763 for (int i=0; i<N; i++) { 14764 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 14765 if (st.pid == findPid || (st.baseName != null 14766 && st.baseName.equals(args[opti]))) { 14767 nativeProcs.add(st); 14768 } 14769 } 14770 } 14771 if (nativeProcs.size() > 0) { 14772 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, 14773 isCompact); 14774 Debug.MemoryInfo mi = null; 14775 for (int i = nativeProcs.size() - 1 ; i >= 0 ; i--) { 14776 final ProcessCpuTracker.Stats r = nativeProcs.get(i); 14777 final int pid = r.pid; 14778 if (!isCheckinRequest && dumpDetails) { 14779 pw.println("\n** MEMINFO in pid " + pid + " [" + r.baseName + "] **"); 14780 } 14781 if (mi == null) { 14782 mi = new Debug.MemoryInfo(); 14783 } 14784 if (dumpDetails || (!brief && !oomOnly)) { 14785 Debug.getMemoryInfo(pid, mi); 14786 } else { 14787 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null); 14788 mi.dalvikPrivateDirty = (int)tmpLong[0]; 14789 } 14790 ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, 14791 dumpDalvik, dumpSummaryOnly, pid, r.baseName, 0, 0, 0, 0, 0, 0); 14792 if (isCheckinRequest) { 14793 pw.println(); 14794 } 14795 } 14796 return; 14797 } 14798 } 14799 pw.println("No process found for: " + args[opti]); 14800 return; 14801 } 14802 14803 if (!brief && !oomOnly && (procs.size() == 1 || isCheckinRequest || packages)) { 14804 dumpDetails = true; 14805 } 14806 14807 dumpApplicationMemoryUsageHeader(pw, uptime, realtime, isCheckinRequest, isCompact); 14808 14809 String[] innerArgs = new String[args.length-opti]; 14810 System.arraycopy(args, opti, innerArgs, 0, args.length-opti); 14811 14812 ArrayList<MemItem> procMems = new ArrayList<MemItem>(); 14813 final SparseArray<MemItem> procMemsMap = new SparseArray<MemItem>(); 14814 long nativePss = 0; 14815 long dalvikPss = 0; 14816 long[] dalvikSubitemPss = dumpDalvik ? new long[Debug.MemoryInfo.NUM_DVK_STATS] : 14817 EmptyArray.LONG; 14818 long otherPss = 0; 14819 long[] miscPss = new long[Debug.MemoryInfo.NUM_OTHER_STATS]; 14820 14821 long oomPss[] = new long[DUMP_MEM_OOM_LABEL.length]; 14822 ArrayList<MemItem>[] oomProcs = (ArrayList<MemItem>[]) 14823 new ArrayList[DUMP_MEM_OOM_LABEL.length]; 14824 14825 long totalPss = 0; 14826 long cachedPss = 0; 14827 14828 Debug.MemoryInfo mi = null; 14829 for (int i = procs.size() - 1 ; i >= 0 ; i--) { 14830 final ProcessRecord r = procs.get(i); 14831 final IApplicationThread thread; 14832 final int pid; 14833 final int oomAdj; 14834 final boolean hasActivities; 14835 synchronized (this) { 14836 thread = r.thread; 14837 pid = r.pid; 14838 oomAdj = r.getSetAdjWithServices(); 14839 hasActivities = r.activities.size() > 0; 14840 } 14841 if (thread != null) { 14842 if (!isCheckinRequest && dumpDetails) { 14843 pw.println("\n** MEMINFO in pid " + pid + " [" + r.processName + "] **"); 14844 } 14845 if (mi == null) { 14846 mi = new Debug.MemoryInfo(); 14847 } 14848 if (dumpDetails || (!brief && !oomOnly)) { 14849 Debug.getMemoryInfo(pid, mi); 14850 } else { 14851 mi.dalvikPss = (int)Debug.getPss(pid, tmpLong, null); 14852 mi.dalvikPrivateDirty = (int)tmpLong[0]; 14853 } 14854 if (dumpDetails) { 14855 if (localOnly) { 14856 ActivityThread.dumpMemInfoTable(pw, mi, isCheckinRequest, dumpFullDetails, 14857 dumpDalvik, dumpSummaryOnly, pid, r.processName, 0, 0, 0, 0, 0, 0); 14858 if (isCheckinRequest) { 14859 pw.println(); 14860 } 14861 } else { 14862 try { 14863 pw.flush(); 14864 thread.dumpMemInfo(fd, mi, isCheckinRequest, dumpFullDetails, 14865 dumpDalvik, dumpSummaryOnly, innerArgs); 14866 } catch (RemoteException e) { 14867 if (!isCheckinRequest) { 14868 pw.println("Got RemoteException!"); 14869 pw.flush(); 14870 } 14871 } 14872 } 14873 } 14874 14875 final long myTotalPss = mi.getTotalPss(); 14876 final long myTotalUss = mi.getTotalUss(); 14877 14878 synchronized (this) { 14879 if (r.thread != null && oomAdj == r.getSetAdjWithServices()) { 14880 // Record this for posterity if the process has been stable. 14881 r.baseProcessTracker.addPss(myTotalPss, myTotalUss, true, r.pkgList); 14882 } 14883 } 14884 14885 if (!isCheckinRequest && mi != null) { 14886 totalPss += myTotalPss; 14887 MemItem pssItem = new MemItem(r.processName + " (pid " + pid + 14888 (hasActivities ? " / activities)" : ")"), 14889 r.processName, myTotalPss, pid, hasActivities); 14890 procMems.add(pssItem); 14891 procMemsMap.put(pid, pssItem); 14892 14893 nativePss += mi.nativePss; 14894 dalvikPss += mi.dalvikPss; 14895 for (int j=0; j<dalvikSubitemPss.length; j++) { 14896 dalvikSubitemPss[j] += mi.getOtherPss(Debug.MemoryInfo.NUM_OTHER_STATS + j); 14897 } 14898 otherPss += mi.otherPss; 14899 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 14900 long mem = mi.getOtherPss(j); 14901 miscPss[j] += mem; 14902 otherPss -= mem; 14903 } 14904 14905 if (oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 14906 cachedPss += myTotalPss; 14907 } 14908 14909 for (int oomIndex=0; oomIndex<oomPss.length; oomIndex++) { 14910 if (oomAdj <= DUMP_MEM_OOM_ADJ[oomIndex] 14911 || oomIndex == (oomPss.length-1)) { 14912 oomPss[oomIndex] += myTotalPss; 14913 if (oomProcs[oomIndex] == null) { 14914 oomProcs[oomIndex] = new ArrayList<MemItem>(); 14915 } 14916 oomProcs[oomIndex].add(pssItem); 14917 break; 14918 } 14919 } 14920 } 14921 } 14922 } 14923 14924 long nativeProcTotalPss = 0; 14925 14926 if (!isCheckinRequest && procs.size() > 1 && !packages) { 14927 // If we are showing aggregations, also look for native processes to 14928 // include so that our aggregations are more accurate. 14929 updateCpuStatsNow(); 14930 mi = null; 14931 synchronized (mProcessCpuTracker) { 14932 final int N = mProcessCpuTracker.countStats(); 14933 for (int i=0; i<N; i++) { 14934 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 14935 if (st.vsize > 0 && procMemsMap.indexOfKey(st.pid) < 0) { 14936 if (mi == null) { 14937 mi = new Debug.MemoryInfo(); 14938 } 14939 if (!brief && !oomOnly) { 14940 Debug.getMemoryInfo(st.pid, mi); 14941 } else { 14942 mi.nativePss = (int)Debug.getPss(st.pid, tmpLong, null); 14943 mi.nativePrivateDirty = (int)tmpLong[0]; 14944 } 14945 14946 final long myTotalPss = mi.getTotalPss(); 14947 totalPss += myTotalPss; 14948 nativeProcTotalPss += myTotalPss; 14949 14950 MemItem pssItem = new MemItem(st.name + " (pid " + st.pid + ")", 14951 st.name, myTotalPss, st.pid, false); 14952 procMems.add(pssItem); 14953 14954 nativePss += mi.nativePss; 14955 dalvikPss += mi.dalvikPss; 14956 for (int j=0; j<dalvikSubitemPss.length; j++) { 14957 dalvikSubitemPss[j] += mi.getOtherPss( 14958 Debug.MemoryInfo.NUM_OTHER_STATS + j); 14959 } 14960 otherPss += mi.otherPss; 14961 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 14962 long mem = mi.getOtherPss(j); 14963 miscPss[j] += mem; 14964 otherPss -= mem; 14965 } 14966 oomPss[0] += myTotalPss; 14967 if (oomProcs[0] == null) { 14968 oomProcs[0] = new ArrayList<MemItem>(); 14969 } 14970 oomProcs[0].add(pssItem); 14971 } 14972 } 14973 } 14974 14975 ArrayList<MemItem> catMems = new ArrayList<MemItem>(); 14976 14977 catMems.add(new MemItem("Native", "Native", nativePss, -1)); 14978 final MemItem dalvikItem = new MemItem("Dalvik", "Dalvik", dalvikPss, -2); 14979 if (dalvikSubitemPss.length > 0) { 14980 dalvikItem.subitems = new ArrayList<MemItem>(); 14981 for (int j=0; j<dalvikSubitemPss.length; j++) { 14982 final String name = Debug.MemoryInfo.getOtherLabel( 14983 Debug.MemoryInfo.NUM_OTHER_STATS + j); 14984 dalvikItem.subitems.add(new MemItem(name, name, dalvikSubitemPss[j], j)); 14985 } 14986 } 14987 catMems.add(dalvikItem); 14988 catMems.add(new MemItem("Unknown", "Unknown", otherPss, -3)); 14989 for (int j=0; j<Debug.MemoryInfo.NUM_OTHER_STATS; j++) { 14990 String label = Debug.MemoryInfo.getOtherLabel(j); 14991 catMems.add(new MemItem(label, label, miscPss[j], j)); 14992 } 14993 14994 ArrayList<MemItem> oomMems = new ArrayList<MemItem>(); 14995 for (int j=0; j<oomPss.length; j++) { 14996 if (oomPss[j] != 0) { 14997 String label = isCompact ? DUMP_MEM_OOM_COMPACT_LABEL[j] 14998 : DUMP_MEM_OOM_LABEL[j]; 14999 MemItem item = new MemItem(label, label, oomPss[j], 15000 DUMP_MEM_OOM_ADJ[j]); 15001 item.subitems = oomProcs[j]; 15002 oomMems.add(item); 15003 } 15004 } 15005 15006 if (!brief && !oomOnly && !isCompact) { 15007 pw.println(); 15008 pw.println("Total PSS by process:"); 15009 dumpMemItems(pw, " ", "proc", procMems, true, isCompact); 15010 pw.println(); 15011 } 15012 if (!isCompact) { 15013 pw.println("Total PSS by OOM adjustment:"); 15014 } 15015 dumpMemItems(pw, " ", "oom", oomMems, false, isCompact); 15016 if (!brief && !oomOnly) { 15017 PrintWriter out = categoryPw != null ? categoryPw : pw; 15018 if (!isCompact) { 15019 out.println(); 15020 out.println("Total PSS by category:"); 15021 } 15022 dumpMemItems(out, " ", "cat", catMems, true, isCompact); 15023 } 15024 if (!isCompact) { 15025 pw.println(); 15026 } 15027 MemInfoReader memInfo = new MemInfoReader(); 15028 memInfo.readMemInfo(); 15029 if (nativeProcTotalPss > 0) { 15030 synchronized (this) { 15031 final long cachedKb = memInfo.getCachedSizeKb(); 15032 final long freeKb = memInfo.getFreeSizeKb(); 15033 final long zramKb = memInfo.getZramTotalSizeKb(); 15034 final long kernelKb = memInfo.getKernelUsedSizeKb(); 15035 EventLogTags.writeAmMeminfo(cachedKb*1024, freeKb*1024, zramKb*1024, 15036 kernelKb*1024, nativeProcTotalPss*1024); 15037 mProcessStats.addSysMemUsageLocked(cachedKb, freeKb, zramKb, kernelKb, 15038 nativeProcTotalPss); 15039 } 15040 } 15041 if (!brief) { 15042 if (!isCompact) { 15043 pw.print("Total RAM: "); pw.print(memInfo.getTotalSizeKb()); 15044 pw.print(" kB (status "); 15045 switch (mLastMemoryLevel) { 15046 case ProcessStats.ADJ_MEM_FACTOR_NORMAL: 15047 pw.println("normal)"); 15048 break; 15049 case ProcessStats.ADJ_MEM_FACTOR_MODERATE: 15050 pw.println("moderate)"); 15051 break; 15052 case ProcessStats.ADJ_MEM_FACTOR_LOW: 15053 pw.println("low)"); 15054 break; 15055 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 15056 pw.println("critical)"); 15057 break; 15058 default: 15059 pw.print(mLastMemoryLevel); 15060 pw.println(")"); 15061 break; 15062 } 15063 pw.print(" Free RAM: "); pw.print(cachedPss + memInfo.getCachedSizeKb() 15064 + memInfo.getFreeSizeKb()); pw.print(" kB ("); 15065 pw.print(cachedPss); pw.print(" cached pss + "); 15066 pw.print(memInfo.getCachedSizeKb()); pw.print(" cached kernel + "); 15067 pw.print(memInfo.getFreeSizeKb()); pw.println(" free)"); 15068 } else { 15069 pw.print("ram,"); pw.print(memInfo.getTotalSizeKb()); pw.print(","); 15070 pw.print(cachedPss + memInfo.getCachedSizeKb() 15071 + memInfo.getFreeSizeKb()); pw.print(","); 15072 pw.println(totalPss - cachedPss); 15073 } 15074 } 15075 if (!isCompact) { 15076 pw.print(" Used RAM: "); pw.print(totalPss - cachedPss 15077 + memInfo.getKernelUsedSizeKb()); pw.print(" kB ("); 15078 pw.print(totalPss - cachedPss); pw.print(" used pss + "); 15079 pw.print(memInfo.getKernelUsedSizeKb()); pw.print(" kernel)\n"); 15080 pw.print(" Lost RAM: "); pw.print(memInfo.getTotalSizeKb() 15081 - totalPss - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 15082 - memInfo.getKernelUsedSizeKb()); pw.println(" kB"); 15083 } 15084 if (!brief) { 15085 if (memInfo.getZramTotalSizeKb() != 0) { 15086 if (!isCompact) { 15087 pw.print(" ZRAM: "); pw.print(memInfo.getZramTotalSizeKb()); 15088 pw.print(" kB physical used for "); 15089 pw.print(memInfo.getSwapTotalSizeKb() 15090 - memInfo.getSwapFreeSizeKb()); 15091 pw.print(" kB in swap ("); 15092 pw.print(memInfo.getSwapTotalSizeKb()); 15093 pw.println(" kB total swap)"); 15094 } else { 15095 pw.print("zram,"); pw.print(memInfo.getZramTotalSizeKb()); pw.print(","); 15096 pw.print(memInfo.getSwapTotalSizeKb()); pw.print(","); 15097 pw.println(memInfo.getSwapFreeSizeKb()); 15098 } 15099 } 15100 final long[] ksm = getKsmInfo(); 15101 if (!isCompact) { 15102 if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 15103 || ksm[KSM_VOLATILE] != 0) { 15104 pw.print(" KSM: "); pw.print(ksm[KSM_SHARING]); 15105 pw.print(" kB saved from shared "); 15106 pw.print(ksm[KSM_SHARED]); pw.println(" kB"); 15107 pw.print(" "); pw.print(ksm[KSM_UNSHARED]); 15108 pw.print(" kB unshared; "); 15109 pw.print(ksm[KSM_VOLATILE]); pw.println(" kB volatile"); 15110 } 15111 pw.print(" Tuning: "); 15112 pw.print(ActivityManager.staticGetMemoryClass()); 15113 pw.print(" (large "); 15114 pw.print(ActivityManager.staticGetLargeMemoryClass()); 15115 pw.print("), oom "); 15116 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 15117 pw.print(" kB"); 15118 pw.print(", restore limit "); 15119 pw.print(mProcessList.getCachedRestoreThresholdKb()); 15120 pw.print(" kB"); 15121 if (ActivityManager.isLowRamDeviceStatic()) { 15122 pw.print(" (low-ram)"); 15123 } 15124 if (ActivityManager.isHighEndGfx()) { 15125 pw.print(" (high-end-gfx)"); 15126 } 15127 pw.println(); 15128 } else { 15129 pw.print("ksm,"); pw.print(ksm[KSM_SHARING]); pw.print(","); 15130 pw.print(ksm[KSM_SHARED]); pw.print(","); pw.print(ksm[KSM_UNSHARED]); 15131 pw.print(","); pw.println(ksm[KSM_VOLATILE]); 15132 pw.print("tuning,"); 15133 pw.print(ActivityManager.staticGetMemoryClass()); 15134 pw.print(','); 15135 pw.print(ActivityManager.staticGetLargeMemoryClass()); 15136 pw.print(','); 15137 pw.print(mProcessList.getMemLevel(ProcessList.CACHED_APP_MAX_ADJ)/1024); 15138 if (ActivityManager.isLowRamDeviceStatic()) { 15139 pw.print(",low-ram"); 15140 } 15141 if (ActivityManager.isHighEndGfx()) { 15142 pw.print(",high-end-gfx"); 15143 } 15144 pw.println(); 15145 } 15146 } 15147 } 15148 } 15149 appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, long memtrack, String name)15150 private void appendBasicMemEntry(StringBuilder sb, int oomAdj, int procState, long pss, 15151 long memtrack, String name) { 15152 sb.append(" "); 15153 sb.append(ProcessList.makeOomAdjString(oomAdj)); 15154 sb.append(' '); 15155 sb.append(ProcessList.makeProcStateString(procState)); 15156 sb.append(' '); 15157 ProcessList.appendRamKb(sb, pss); 15158 sb.append(" kB: "); 15159 sb.append(name); 15160 if (memtrack > 0) { 15161 sb.append(" ("); 15162 sb.append(memtrack); 15163 sb.append(" kB memtrack)"); 15164 } 15165 } 15166 appendMemInfo(StringBuilder sb, ProcessMemInfo mi)15167 private void appendMemInfo(StringBuilder sb, ProcessMemInfo mi) { 15168 appendBasicMemEntry(sb, mi.oomAdj, mi.procState, mi.pss, mi.memtrack, mi.name); 15169 sb.append(" (pid "); 15170 sb.append(mi.pid); 15171 sb.append(") "); 15172 sb.append(mi.adjType); 15173 sb.append('\n'); 15174 if (mi.adjReason != null) { 15175 sb.append(" "); 15176 sb.append(mi.adjReason); 15177 sb.append('\n'); 15178 } 15179 } 15180 reportMemUsage(ArrayList<ProcessMemInfo> memInfos)15181 void reportMemUsage(ArrayList<ProcessMemInfo> memInfos) { 15182 final SparseArray<ProcessMemInfo> infoMap = new SparseArray<>(memInfos.size()); 15183 for (int i=0, N=memInfos.size(); i<N; i++) { 15184 ProcessMemInfo mi = memInfos.get(i); 15185 infoMap.put(mi.pid, mi); 15186 } 15187 updateCpuStatsNow(); 15188 long[] memtrackTmp = new long[1]; 15189 synchronized (mProcessCpuTracker) { 15190 final int N = mProcessCpuTracker.countStats(); 15191 for (int i=0; i<N; i++) { 15192 ProcessCpuTracker.Stats st = mProcessCpuTracker.getStats(i); 15193 if (st.vsize > 0) { 15194 long pss = Debug.getPss(st.pid, null, memtrackTmp); 15195 if (pss > 0) { 15196 if (infoMap.indexOfKey(st.pid) < 0) { 15197 ProcessMemInfo mi = new ProcessMemInfo(st.name, st.pid, 15198 ProcessList.NATIVE_ADJ, -1, "native", null); 15199 mi.pss = pss; 15200 mi.memtrack = memtrackTmp[0]; 15201 memInfos.add(mi); 15202 } 15203 } 15204 } 15205 } 15206 } 15207 15208 long totalPss = 0; 15209 long totalMemtrack = 0; 15210 for (int i=0, N=memInfos.size(); i<N; i++) { 15211 ProcessMemInfo mi = memInfos.get(i); 15212 if (mi.pss == 0) { 15213 mi.pss = Debug.getPss(mi.pid, null, memtrackTmp); 15214 mi.memtrack = memtrackTmp[0]; 15215 } 15216 totalPss += mi.pss; 15217 totalMemtrack += mi.memtrack; 15218 } 15219 Collections.sort(memInfos, new Comparator<ProcessMemInfo>() { 15220 @Override public int compare(ProcessMemInfo lhs, ProcessMemInfo rhs) { 15221 if (lhs.oomAdj != rhs.oomAdj) { 15222 return lhs.oomAdj < rhs.oomAdj ? -1 : 1; 15223 } 15224 if (lhs.pss != rhs.pss) { 15225 return lhs.pss < rhs.pss ? 1 : -1; 15226 } 15227 return 0; 15228 } 15229 }); 15230 15231 StringBuilder tag = new StringBuilder(128); 15232 StringBuilder stack = new StringBuilder(128); 15233 tag.append("Low on memory -- "); 15234 appendMemBucket(tag, totalPss, "total", false); 15235 appendMemBucket(stack, totalPss, "total", true); 15236 15237 StringBuilder fullNativeBuilder = new StringBuilder(1024); 15238 StringBuilder shortNativeBuilder = new StringBuilder(1024); 15239 StringBuilder fullJavaBuilder = new StringBuilder(1024); 15240 15241 boolean firstLine = true; 15242 int lastOomAdj = Integer.MIN_VALUE; 15243 long extraNativeRam = 0; 15244 long extraNativeMemtrack = 0; 15245 long cachedPss = 0; 15246 for (int i=0, N=memInfos.size(); i<N; i++) { 15247 ProcessMemInfo mi = memInfos.get(i); 15248 15249 if (mi.oomAdj >= ProcessList.CACHED_APP_MIN_ADJ) { 15250 cachedPss += mi.pss; 15251 } 15252 15253 if (mi.oomAdj != ProcessList.NATIVE_ADJ 15254 && (mi.oomAdj < ProcessList.SERVICE_ADJ 15255 || mi.oomAdj == ProcessList.HOME_APP_ADJ 15256 || mi.oomAdj == ProcessList.PREVIOUS_APP_ADJ)) { 15257 if (lastOomAdj != mi.oomAdj) { 15258 lastOomAdj = mi.oomAdj; 15259 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) { 15260 tag.append(" / "); 15261 } 15262 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ) { 15263 if (firstLine) { 15264 stack.append(":"); 15265 firstLine = false; 15266 } 15267 stack.append("\n\t at "); 15268 } else { 15269 stack.append("$"); 15270 } 15271 } else { 15272 tag.append(" "); 15273 stack.append("$"); 15274 } 15275 if (mi.oomAdj <= ProcessList.FOREGROUND_APP_ADJ) { 15276 appendMemBucket(tag, mi.pss, mi.name, false); 15277 } 15278 appendMemBucket(stack, mi.pss, mi.name, true); 15279 if (mi.oomAdj >= ProcessList.FOREGROUND_APP_ADJ 15280 && ((i+1) >= N || memInfos.get(i+1).oomAdj != lastOomAdj)) { 15281 stack.append("("); 15282 for (int k=0; k<DUMP_MEM_OOM_ADJ.length; k++) { 15283 if (DUMP_MEM_OOM_ADJ[k] == mi.oomAdj) { 15284 stack.append(DUMP_MEM_OOM_LABEL[k]); 15285 stack.append(":"); 15286 stack.append(DUMP_MEM_OOM_ADJ[k]); 15287 } 15288 } 15289 stack.append(")"); 15290 } 15291 } 15292 15293 appendMemInfo(fullNativeBuilder, mi); 15294 if (mi.oomAdj == ProcessList.NATIVE_ADJ) { 15295 // The short form only has native processes that are >= 512K. 15296 if (mi.pss >= 512) { 15297 appendMemInfo(shortNativeBuilder, mi); 15298 } else { 15299 extraNativeRam += mi.pss; 15300 extraNativeMemtrack += mi.memtrack; 15301 } 15302 } else { 15303 // Short form has all other details, but if we have collected RAM 15304 // from smaller native processes let's dump a summary of that. 15305 if (extraNativeRam > 0) { 15306 appendBasicMemEntry(shortNativeBuilder, ProcessList.NATIVE_ADJ, 15307 -1, extraNativeRam, extraNativeMemtrack, "(Other native)"); 15308 shortNativeBuilder.append('\n'); 15309 extraNativeRam = 0; 15310 } 15311 appendMemInfo(fullJavaBuilder, mi); 15312 } 15313 } 15314 15315 fullJavaBuilder.append(" "); 15316 ProcessList.appendRamKb(fullJavaBuilder, totalPss); 15317 fullJavaBuilder.append(" kB: TOTAL"); 15318 if (totalMemtrack > 0) { 15319 fullJavaBuilder.append(" ("); 15320 fullJavaBuilder.append(totalMemtrack); 15321 fullJavaBuilder.append(" kB memtrack)"); 15322 } else { 15323 } 15324 fullJavaBuilder.append("\n"); 15325 15326 MemInfoReader memInfo = new MemInfoReader(); 15327 memInfo.readMemInfo(); 15328 final long[] infos = memInfo.getRawInfo(); 15329 15330 StringBuilder memInfoBuilder = new StringBuilder(1024); 15331 Debug.getMemInfo(infos); 15332 memInfoBuilder.append(" MemInfo: "); 15333 memInfoBuilder.append(infos[Debug.MEMINFO_SLAB]).append(" kB slab, "); 15334 memInfoBuilder.append(infos[Debug.MEMINFO_SHMEM]).append(" kB shmem, "); 15335 memInfoBuilder.append(infos[Debug.MEMINFO_VM_ALLOC_USED]).append(" kB vm alloc, "); 15336 memInfoBuilder.append(infos[Debug.MEMINFO_PAGE_TABLES]).append(" kB page tables "); 15337 memInfoBuilder.append(infos[Debug.MEMINFO_KERNEL_STACK]).append(" kB kernel stack\n"); 15338 memInfoBuilder.append(" "); 15339 memInfoBuilder.append(infos[Debug.MEMINFO_BUFFERS]).append(" kB buffers, "); 15340 memInfoBuilder.append(infos[Debug.MEMINFO_CACHED]).append(" kB cached, "); 15341 memInfoBuilder.append(infos[Debug.MEMINFO_MAPPED]).append(" kB mapped, "); 15342 memInfoBuilder.append(infos[Debug.MEMINFO_FREE]).append(" kB free\n"); 15343 if (infos[Debug.MEMINFO_ZRAM_TOTAL] != 0) { 15344 memInfoBuilder.append(" ZRAM: "); 15345 memInfoBuilder.append(infos[Debug.MEMINFO_ZRAM_TOTAL]); 15346 memInfoBuilder.append(" kB RAM, "); 15347 memInfoBuilder.append(infos[Debug.MEMINFO_SWAP_TOTAL]); 15348 memInfoBuilder.append(" kB swap total, "); 15349 memInfoBuilder.append(infos[Debug.MEMINFO_SWAP_FREE]); 15350 memInfoBuilder.append(" kB swap free\n"); 15351 } 15352 final long[] ksm = getKsmInfo(); 15353 if (ksm[KSM_SHARING] != 0 || ksm[KSM_SHARED] != 0 || ksm[KSM_UNSHARED] != 0 15354 || ksm[KSM_VOLATILE] != 0) { 15355 memInfoBuilder.append(" KSM: "); memInfoBuilder.append(ksm[KSM_SHARING]); 15356 memInfoBuilder.append(" kB saved from shared "); 15357 memInfoBuilder.append(ksm[KSM_SHARED]); memInfoBuilder.append(" kB\n"); 15358 memInfoBuilder.append(" "); memInfoBuilder.append(ksm[KSM_UNSHARED]); 15359 memInfoBuilder.append(" kB unshared; "); 15360 memInfoBuilder.append(ksm[KSM_VOLATILE]); memInfoBuilder.append(" kB volatile\n"); 15361 } 15362 memInfoBuilder.append(" Free RAM: "); 15363 memInfoBuilder.append(cachedPss + memInfo.getCachedSizeKb() 15364 + memInfo.getFreeSizeKb()); 15365 memInfoBuilder.append(" kB\n"); 15366 memInfoBuilder.append(" Used RAM: "); 15367 memInfoBuilder.append(totalPss - cachedPss + memInfo.getKernelUsedSizeKb()); 15368 memInfoBuilder.append(" kB\n"); 15369 memInfoBuilder.append(" Lost RAM: "); 15370 memInfoBuilder.append(memInfo.getTotalSizeKb() 15371 - totalPss - memInfo.getFreeSizeKb() - memInfo.getCachedSizeKb() 15372 - memInfo.getKernelUsedSizeKb()); 15373 memInfoBuilder.append(" kB\n"); 15374 Slog.i(TAG, "Low on memory:"); 15375 Slog.i(TAG, shortNativeBuilder.toString()); 15376 Slog.i(TAG, fullJavaBuilder.toString()); 15377 Slog.i(TAG, memInfoBuilder.toString()); 15378 15379 StringBuilder dropBuilder = new StringBuilder(1024); 15380 /* 15381 StringWriter oomSw = new StringWriter(); 15382 PrintWriter oomPw = new FastPrintWriter(oomSw, false, 256); 15383 StringWriter catSw = new StringWriter(); 15384 PrintWriter catPw = new FastPrintWriter(catSw, false, 256); 15385 String[] emptyArgs = new String[] { }; 15386 dumpApplicationMemoryUsage(null, oomPw, " ", emptyArgs, true, catPw); 15387 oomPw.flush(); 15388 String oomString = oomSw.toString(); 15389 */ 15390 dropBuilder.append("Low on memory:"); 15391 dropBuilder.append(stack); 15392 dropBuilder.append('\n'); 15393 dropBuilder.append(fullNativeBuilder); 15394 dropBuilder.append(fullJavaBuilder); 15395 dropBuilder.append('\n'); 15396 dropBuilder.append(memInfoBuilder); 15397 dropBuilder.append('\n'); 15398 /* 15399 dropBuilder.append(oomString); 15400 dropBuilder.append('\n'); 15401 */ 15402 StringWriter catSw = new StringWriter(); 15403 synchronized (ActivityManagerService.this) { 15404 PrintWriter catPw = new FastPrintWriter(catSw, false, 256); 15405 String[] emptyArgs = new String[] { }; 15406 catPw.println(); 15407 dumpProcessesLocked(null, catPw, emptyArgs, 0, false, null); 15408 catPw.println(); 15409 mServices.dumpServicesLocked(null, catPw, emptyArgs, 0, 15410 false, false, null); 15411 catPw.println(); 15412 dumpActivitiesLocked(null, catPw, emptyArgs, 0, false, false, null); 15413 catPw.flush(); 15414 } 15415 dropBuilder.append(catSw.toString()); 15416 addErrorToDropBox("lowmem", null, "system_server", null, 15417 null, tag.toString(), dropBuilder.toString(), null, null); 15418 //Slog.i(TAG, "Sent to dropbox:"); 15419 //Slog.i(TAG, dropBuilder.toString()); 15420 synchronized (ActivityManagerService.this) { 15421 long now = SystemClock.uptimeMillis(); 15422 if (mLastMemUsageReportTime < now) { 15423 mLastMemUsageReportTime = now; 15424 } 15425 } 15426 } 15427 15428 /** 15429 * Searches array of arguments for the specified string 15430 * @param args array of argument strings 15431 * @param value value to search for 15432 * @return true if the value is contained in the array 15433 */ scanArgs(String[] args, String value)15434 private static boolean scanArgs(String[] args, String value) { 15435 if (args != null) { 15436 for (String arg : args) { 15437 if (value.equals(arg)) { 15438 return true; 15439 } 15440 } 15441 } 15442 return false; 15443 } 15444 removeDyingProviderLocked(ProcessRecord proc, ContentProviderRecord cpr, boolean always)15445 private final boolean removeDyingProviderLocked(ProcessRecord proc, 15446 ContentProviderRecord cpr, boolean always) { 15447 final boolean inLaunching = mLaunchingProviders.contains(cpr); 15448 15449 if (!inLaunching || always) { 15450 synchronized (cpr) { 15451 cpr.launchingApp = null; 15452 cpr.notifyAll(); 15453 } 15454 mProviderMap.removeProviderByClass(cpr.name, UserHandle.getUserId(cpr.uid)); 15455 String names[] = cpr.info.authority.split(";"); 15456 for (int j = 0; j < names.length; j++) { 15457 mProviderMap.removeProviderByName(names[j], UserHandle.getUserId(cpr.uid)); 15458 } 15459 } 15460 15461 for (int i = cpr.connections.size() - 1; i >= 0; i--) { 15462 ContentProviderConnection conn = cpr.connections.get(i); 15463 if (conn.waiting) { 15464 // If this connection is waiting for the provider, then we don't 15465 // need to mess with its process unless we are always removing 15466 // or for some reason the provider is not currently launching. 15467 if (inLaunching && !always) { 15468 continue; 15469 } 15470 } 15471 ProcessRecord capp = conn.client; 15472 conn.dead = true; 15473 if (conn.stableCount > 0) { 15474 if (!capp.persistent && capp.thread != null 15475 && capp.pid != 0 15476 && capp.pid != MY_PID) { 15477 capp.kill("depends on provider " 15478 + cpr.name.flattenToShortString() 15479 + " in dying proc " + (proc != null ? proc.processName : "??"), true); 15480 } 15481 } else if (capp.thread != null && conn.provider.provider != null) { 15482 try { 15483 capp.thread.unstableProviderDied(conn.provider.provider.asBinder()); 15484 } catch (RemoteException e) { 15485 } 15486 // In the protocol here, we don't expect the client to correctly 15487 // clean up this connection, we'll just remove it. 15488 cpr.connections.remove(i); 15489 if (conn.client.conProviders.remove(conn)) { 15490 stopAssociationLocked(capp.uid, capp.processName, cpr.uid, cpr.name); 15491 } 15492 } 15493 } 15494 15495 if (inLaunching && always) { 15496 mLaunchingProviders.remove(cpr); 15497 } 15498 return inLaunching; 15499 } 15500 15501 /** 15502 * Main code for cleaning up a process when it has gone away. This is 15503 * called both as a result of the process dying, or directly when stopping 15504 * a process when running in single process mode. 15505 * 15506 * @return Returns true if the given process has been restarted, so the 15507 * app that was passed in must remain on the process lists. 15508 */ cleanUpApplicationRecordLocked(ProcessRecord app, boolean restarting, boolean allowRestart, int index)15509 private final boolean cleanUpApplicationRecordLocked(ProcessRecord app, 15510 boolean restarting, boolean allowRestart, int index) { 15511 if (index >= 0) { 15512 removeLruProcessLocked(app); 15513 ProcessList.remove(app.pid); 15514 } 15515 15516 mProcessesToGc.remove(app); 15517 mPendingPssProcesses.remove(app); 15518 15519 // Dismiss any open dialogs. 15520 if (app.crashDialog != null && !app.forceCrashReport) { 15521 app.crashDialog.dismiss(); 15522 app.crashDialog = null; 15523 } 15524 if (app.anrDialog != null) { 15525 app.anrDialog.dismiss(); 15526 app.anrDialog = null; 15527 } 15528 if (app.waitDialog != null) { 15529 app.waitDialog.dismiss(); 15530 app.waitDialog = null; 15531 } 15532 15533 app.crashing = false; 15534 app.notResponding = false; 15535 15536 app.resetPackageList(mProcessStats); 15537 app.unlinkDeathRecipient(); 15538 app.makeInactive(mProcessStats); 15539 app.waitingToKill = null; 15540 app.forcingToForeground = null; 15541 updateProcessForegroundLocked(app, false, false); 15542 app.foregroundActivities = false; 15543 app.hasShownUi = false; 15544 app.treatLikeActivity = false; 15545 app.hasAboveClient = false; 15546 app.hasClientActivities = false; 15547 15548 mServices.killServicesLocked(app, allowRestart); 15549 15550 boolean restart = false; 15551 15552 // Remove published content providers. 15553 for (int i = app.pubProviders.size() - 1; i >= 0; i--) { 15554 ContentProviderRecord cpr = app.pubProviders.valueAt(i); 15555 final boolean always = app.bad || !allowRestart; 15556 boolean inLaunching = removeDyingProviderLocked(app, cpr, always); 15557 if ((inLaunching || always) && cpr.hasConnectionOrHandle()) { 15558 // We left the provider in the launching list, need to 15559 // restart it. 15560 restart = true; 15561 } 15562 15563 cpr.provider = null; 15564 cpr.proc = null; 15565 } 15566 app.pubProviders.clear(); 15567 15568 // Take care of any launching providers waiting for this process. 15569 if (cleanupAppInLaunchingProvidersLocked(app, false)) { 15570 restart = true; 15571 } 15572 15573 // Unregister from connected content providers. 15574 if (!app.conProviders.isEmpty()) { 15575 for (int i = app.conProviders.size() - 1; i >= 0; i--) { 15576 ContentProviderConnection conn = app.conProviders.get(i); 15577 conn.provider.connections.remove(conn); 15578 stopAssociationLocked(app.uid, app.processName, conn.provider.uid, 15579 conn.provider.name); 15580 } 15581 app.conProviders.clear(); 15582 } 15583 15584 // At this point there may be remaining entries in mLaunchingProviders 15585 // where we were the only one waiting, so they are no longer of use. 15586 // Look for these and clean up if found. 15587 // XXX Commented out for now. Trying to figure out a way to reproduce 15588 // the actual situation to identify what is actually going on. 15589 if (false) { 15590 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 15591 ContentProviderRecord cpr = mLaunchingProviders.get(i); 15592 if (cpr.connections.size() <= 0 && !cpr.hasExternalProcessHandles()) { 15593 synchronized (cpr) { 15594 cpr.launchingApp = null; 15595 cpr.notifyAll(); 15596 } 15597 } 15598 } 15599 } 15600 15601 skipCurrentReceiverLocked(app); 15602 15603 // Unregister any receivers. 15604 for (int i = app.receivers.size() - 1; i >= 0; i--) { 15605 removeReceiverLocked(app.receivers.valueAt(i)); 15606 } 15607 app.receivers.clear(); 15608 15609 // If the app is undergoing backup, tell the backup manager about it 15610 if (mBackupTarget != null && app.pid == mBackupTarget.app.pid) { 15611 if (DEBUG_BACKUP || DEBUG_CLEANUP) Slog.d(TAG_CLEANUP, "App " 15612 + mBackupTarget.appInfo + " died during backup"); 15613 try { 15614 IBackupManager bm = IBackupManager.Stub.asInterface( 15615 ServiceManager.getService(Context.BACKUP_SERVICE)); 15616 bm.agentDisconnected(app.info.packageName); 15617 } catch (RemoteException e) { 15618 // can't happen; backup manager is local 15619 } 15620 } 15621 15622 for (int i = mPendingProcessChanges.size() - 1; i >= 0; i--) { 15623 ProcessChangeItem item = mPendingProcessChanges.get(i); 15624 if (item.pid == app.pid) { 15625 mPendingProcessChanges.remove(i); 15626 mAvailProcessChanges.add(item); 15627 } 15628 } 15629 mUiHandler.obtainMessage(DISPATCH_PROCESS_DIED, app.pid, app.info.uid, null).sendToTarget(); 15630 15631 // If the caller is restarting this app, then leave it in its 15632 // current lists and let the caller take care of it. 15633 if (restarting) { 15634 return false; 15635 } 15636 15637 if (!app.persistent || app.isolated) { 15638 if (DEBUG_PROCESSES || DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, 15639 "Removing non-persistent process during cleanup: " + app); 15640 removeProcessNameLocked(app.processName, app.uid); 15641 if (mHeavyWeightProcess == app) { 15642 mHandler.sendMessage(mHandler.obtainMessage(CANCEL_HEAVY_NOTIFICATION_MSG, 15643 mHeavyWeightProcess.userId, 0)); 15644 mHeavyWeightProcess = null; 15645 } 15646 } else if (!app.removed) { 15647 // This app is persistent, so we need to keep its record around. 15648 // If it is not already on the pending app list, add it there 15649 // and start a new process for it. 15650 if (mPersistentStartingProcesses.indexOf(app) < 0) { 15651 mPersistentStartingProcesses.add(app); 15652 restart = true; 15653 } 15654 } 15655 if ((DEBUG_PROCESSES || DEBUG_CLEANUP) && mProcessesOnHold.contains(app)) Slog.v( 15656 TAG_CLEANUP, "Clean-up removing on hold: " + app); 15657 mProcessesOnHold.remove(app); 15658 15659 if (app == mHomeProcess) { 15660 mHomeProcess = null; 15661 } 15662 if (app == mPreviousProcess) { 15663 mPreviousProcess = null; 15664 } 15665 15666 if (restart && !app.isolated) { 15667 // We have components that still need to be running in the 15668 // process, so re-launch it. 15669 if (index < 0) { 15670 ProcessList.remove(app.pid); 15671 } 15672 addProcessNameLocked(app); 15673 startProcessLocked(app, "restart", app.processName); 15674 return true; 15675 } else if (app.pid > 0 && app.pid != MY_PID) { 15676 // Goodbye! 15677 boolean removed; 15678 synchronized (mPidsSelfLocked) { 15679 mPidsSelfLocked.remove(app.pid); 15680 mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app); 15681 } 15682 mBatteryStatsService.noteProcessFinish(app.processName, app.info.uid); 15683 if (app.isolated) { 15684 mBatteryStatsService.removeIsolatedUid(app.uid, app.info.uid); 15685 } 15686 app.setPid(0); 15687 } 15688 return false; 15689 } 15690 checkAppInLaunchingProvidersLocked(ProcessRecord app)15691 boolean checkAppInLaunchingProvidersLocked(ProcessRecord app) { 15692 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 15693 ContentProviderRecord cpr = mLaunchingProviders.get(i); 15694 if (cpr.launchingApp == app) { 15695 return true; 15696 } 15697 } 15698 return false; 15699 } 15700 cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad)15701 boolean cleanupAppInLaunchingProvidersLocked(ProcessRecord app, boolean alwaysBad) { 15702 // Look through the content providers we are waiting to have launched, 15703 // and if any run in this process then either schedule a restart of 15704 // the process or kill the client waiting for it if this process has 15705 // gone bad. 15706 boolean restart = false; 15707 for (int i = mLaunchingProviders.size() - 1; i >= 0; i--) { 15708 ContentProviderRecord cpr = mLaunchingProviders.get(i); 15709 if (cpr.launchingApp == app) { 15710 if (!alwaysBad && !app.bad && cpr.hasConnectionOrHandle()) { 15711 restart = true; 15712 } else { 15713 removeDyingProviderLocked(app, cpr, true); 15714 } 15715 } 15716 } 15717 return restart; 15718 } 15719 15720 // ========================================================= 15721 // SERVICES 15722 // ========================================================= 15723 15724 @Override getServices(int maxNum, int flags)15725 public List<ActivityManager.RunningServiceInfo> getServices(int maxNum, 15726 int flags) { 15727 enforceNotIsolatedCaller("getServices"); 15728 synchronized (this) { 15729 return mServices.getRunningServiceInfoLocked(maxNum, flags); 15730 } 15731 } 15732 15733 @Override getRunningServiceControlPanel(ComponentName name)15734 public PendingIntent getRunningServiceControlPanel(ComponentName name) { 15735 enforceNotIsolatedCaller("getRunningServiceControlPanel"); 15736 synchronized (this) { 15737 return mServices.getRunningServiceControlPanelLocked(name); 15738 } 15739 } 15740 15741 @Override startService(IApplicationThread caller, Intent service, String resolvedType, String callingPackage, int userId)15742 public ComponentName startService(IApplicationThread caller, Intent service, 15743 String resolvedType, String callingPackage, int userId) 15744 throws TransactionTooLargeException { 15745 enforceNotIsolatedCaller("startService"); 15746 // Refuse possible leaked file descriptors 15747 if (service != null && service.hasFileDescriptors() == true) { 15748 throw new IllegalArgumentException("File descriptors passed in Intent"); 15749 } 15750 15751 if (callingPackage == null) { 15752 throw new IllegalArgumentException("callingPackage cannot be null"); 15753 } 15754 15755 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 15756 "startService: " + service + " type=" + resolvedType); 15757 synchronized(this) { 15758 final int callingPid = Binder.getCallingPid(); 15759 final int callingUid = Binder.getCallingUid(); 15760 final long origId = Binder.clearCallingIdentity(); 15761 ComponentName res = mServices.startServiceLocked(caller, service, 15762 resolvedType, callingPid, callingUid, callingPackage, userId); 15763 Binder.restoreCallingIdentity(origId); 15764 return res; 15765 } 15766 } 15767 startServiceInPackage(int uid, Intent service, String resolvedType, String callingPackage, int userId)15768 ComponentName startServiceInPackage(int uid, Intent service, String resolvedType, 15769 String callingPackage, int userId) 15770 throws TransactionTooLargeException { 15771 synchronized(this) { 15772 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, 15773 "startServiceInPackage: " + service + " type=" + resolvedType); 15774 final long origId = Binder.clearCallingIdentity(); 15775 ComponentName res = mServices.startServiceLocked(null, service, 15776 resolvedType, -1, uid, callingPackage, userId); 15777 Binder.restoreCallingIdentity(origId); 15778 return res; 15779 } 15780 } 15781 15782 @Override stopService(IApplicationThread caller, Intent service, String resolvedType, int userId)15783 public int stopService(IApplicationThread caller, Intent service, 15784 String resolvedType, int userId) { 15785 enforceNotIsolatedCaller("stopService"); 15786 // Refuse possible leaked file descriptors 15787 if (service != null && service.hasFileDescriptors() == true) { 15788 throw new IllegalArgumentException("File descriptors passed in Intent"); 15789 } 15790 15791 synchronized(this) { 15792 return mServices.stopServiceLocked(caller, service, resolvedType, userId); 15793 } 15794 } 15795 15796 @Override peekService(Intent service, String resolvedType, String callingPackage)15797 public IBinder peekService(Intent service, String resolvedType, String callingPackage) { 15798 enforceNotIsolatedCaller("peekService"); 15799 // Refuse possible leaked file descriptors 15800 if (service != null && service.hasFileDescriptors() == true) { 15801 throw new IllegalArgumentException("File descriptors passed in Intent"); 15802 } 15803 15804 if (callingPackage == null) { 15805 throw new IllegalArgumentException("callingPackage cannot be null"); 15806 } 15807 15808 synchronized(this) { 15809 return mServices.peekServiceLocked(service, resolvedType, callingPackage); 15810 } 15811 } 15812 15813 @Override stopServiceToken(ComponentName className, IBinder token, int startId)15814 public boolean stopServiceToken(ComponentName className, IBinder token, 15815 int startId) { 15816 synchronized(this) { 15817 return mServices.stopServiceTokenLocked(className, token, startId); 15818 } 15819 } 15820 15821 @Override setServiceForeground(ComponentName className, IBinder token, int id, Notification notification, boolean removeNotification)15822 public void setServiceForeground(ComponentName className, IBinder token, 15823 int id, Notification notification, boolean removeNotification) { 15824 synchronized(this) { 15825 mServices.setServiceForegroundLocked(className, token, id, notification, 15826 removeNotification); 15827 } 15828 } 15829 15830 @Override handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, boolean requireFull, String name, String callerPackage)15831 public int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 15832 boolean requireFull, String name, String callerPackage) { 15833 return handleIncomingUser(callingPid, callingUid, userId, allowAll, 15834 requireFull ? ALLOW_FULL_ONLY : ALLOW_NON_FULL, name, callerPackage); 15835 } 15836 unsafeConvertIncomingUser(int userId)15837 int unsafeConvertIncomingUser(int userId) { 15838 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF) 15839 ? mCurrentUserId : userId; 15840 } 15841 handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, int allowMode, String name, String callerPackage)15842 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll, 15843 int allowMode, String name, String callerPackage) { 15844 final int callingUserId = UserHandle.getUserId(callingUid); 15845 if (callingUserId == userId) { 15846 return userId; 15847 } 15848 15849 // Note that we may be accessing mCurrentUserId outside of a lock... 15850 // shouldn't be a big deal, if this is being called outside 15851 // of a locked context there is intrinsically a race with 15852 // the value the caller will receive and someone else changing it. 15853 // We assume that USER_CURRENT_OR_SELF will use the current user; later 15854 // we will switch to the calling user if access to the current user fails. 15855 int targetUserId = unsafeConvertIncomingUser(userId); 15856 15857 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 15858 final boolean allow; 15859 if (checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid, 15860 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) { 15861 // If the caller has this permission, they always pass go. And collect $200. 15862 allow = true; 15863 } else if (allowMode == ALLOW_FULL_ONLY) { 15864 // We require full access, sucks to be you. 15865 allow = false; 15866 } else if (checkComponentPermission(INTERACT_ACROSS_USERS, callingPid, 15867 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) { 15868 // If the caller does not have either permission, they are always doomed. 15869 allow = false; 15870 } else if (allowMode == ALLOW_NON_FULL) { 15871 // We are blanket allowing non-full access, you lucky caller! 15872 allow = true; 15873 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) { 15874 // We may or may not allow this depending on whether the two users are 15875 // in the same profile. 15876 synchronized (mUserProfileGroupIdsSelfLocked) { 15877 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId, 15878 UserInfo.NO_PROFILE_GROUP_ID); 15879 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId, 15880 UserInfo.NO_PROFILE_GROUP_ID); 15881 allow = callingProfile != UserInfo.NO_PROFILE_GROUP_ID 15882 && callingProfile == targetProfile; 15883 } 15884 } else { 15885 throw new IllegalArgumentException("Unknown mode: " + allowMode); 15886 } 15887 if (!allow) { 15888 if (userId == UserHandle.USER_CURRENT_OR_SELF) { 15889 // In this case, they would like to just execute as their 15890 // owner user instead of failing. 15891 targetUserId = callingUserId; 15892 } else { 15893 StringBuilder builder = new StringBuilder(128); 15894 builder.append("Permission Denial: "); 15895 builder.append(name); 15896 if (callerPackage != null) { 15897 builder.append(" from "); 15898 builder.append(callerPackage); 15899 } 15900 builder.append(" asks to run as user "); 15901 builder.append(userId); 15902 builder.append(" but is calling from user "); 15903 builder.append(UserHandle.getUserId(callingUid)); 15904 builder.append("; this requires "); 15905 builder.append(INTERACT_ACROSS_USERS_FULL); 15906 if (allowMode != ALLOW_FULL_ONLY) { 15907 builder.append(" or "); 15908 builder.append(INTERACT_ACROSS_USERS); 15909 } 15910 String msg = builder.toString(); 15911 Slog.w(TAG, msg); 15912 throw new SecurityException(msg); 15913 } 15914 } 15915 } 15916 if (!allowAll && targetUserId < 0) { 15917 throw new IllegalArgumentException( 15918 "Call does not support special user #" + targetUserId); 15919 } 15920 // Check shell permission 15921 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_OWNER) { 15922 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, 15923 targetUserId)) { 15924 throw new SecurityException("Shell does not have permission to access user " 15925 + targetUserId + "\n " + Debug.getCallers(3)); 15926 } 15927 } 15928 return targetUserId; 15929 } 15930 isSingleton(String componentProcessName, ApplicationInfo aInfo, String className, int flags)15931 boolean isSingleton(String componentProcessName, ApplicationInfo aInfo, 15932 String className, int flags) { 15933 boolean result = false; 15934 // For apps that don't have pre-defined UIDs, check for permission 15935 if (UserHandle.getAppId(aInfo.uid) >= Process.FIRST_APPLICATION_UID) { 15936 if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 15937 if (ActivityManager.checkUidPermission( 15938 INTERACT_ACROSS_USERS, 15939 aInfo.uid) != PackageManager.PERMISSION_GRANTED) { 15940 ComponentName comp = new ComponentName(aInfo.packageName, className); 15941 String msg = "Permission Denial: Component " + comp.flattenToShortString() 15942 + " requests FLAG_SINGLE_USER, but app does not hold " 15943 + INTERACT_ACROSS_USERS; 15944 Slog.w(TAG, msg); 15945 throw new SecurityException(msg); 15946 } 15947 // Permission passed 15948 result = true; 15949 } 15950 } else if ("system".equals(componentProcessName)) { 15951 result = true; 15952 } else if ((flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 15953 // Phone app and persistent apps are allowed to export singleuser providers. 15954 result = UserHandle.isSameApp(aInfo.uid, Process.PHONE_UID) 15955 || (aInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0; 15956 } 15957 if (DEBUG_MU) Slog.v(TAG_MU, 15958 "isSingleton(" + componentProcessName + ", " + aInfo + ", " + className + ", 0x" 15959 + Integer.toHexString(flags) + ") = " + result); 15960 return result; 15961 } 15962 15963 /** 15964 * Checks to see if the caller is in the same app as the singleton 15965 * component, or the component is in a special app. It allows special apps 15966 * to export singleton components but prevents exporting singleton 15967 * components for regular apps. 15968 */ isValidSingletonCall(int callingUid, int componentUid)15969 boolean isValidSingletonCall(int callingUid, int componentUid) { 15970 int componentAppId = UserHandle.getAppId(componentUid); 15971 return UserHandle.isSameApp(callingUid, componentUid) 15972 || componentAppId == Process.SYSTEM_UID 15973 || componentAppId == Process.PHONE_UID 15974 || ActivityManager.checkUidPermission(INTERACT_ACROSS_USERS_FULL, componentUid) 15975 == PackageManager.PERMISSION_GRANTED; 15976 } 15977 bindService(IApplicationThread caller, IBinder token, Intent service, String resolvedType, IServiceConnection connection, int flags, String callingPackage, int userId)15978 public int bindService(IApplicationThread caller, IBinder token, Intent service, 15979 String resolvedType, IServiceConnection connection, int flags, String callingPackage, 15980 int userId) throws TransactionTooLargeException { 15981 enforceNotIsolatedCaller("bindService"); 15982 15983 // Refuse possible leaked file descriptors 15984 if (service != null && service.hasFileDescriptors() == true) { 15985 throw new IllegalArgumentException("File descriptors passed in Intent"); 15986 } 15987 15988 if (callingPackage == null) { 15989 throw new IllegalArgumentException("callingPackage cannot be null"); 15990 } 15991 15992 synchronized(this) { 15993 return mServices.bindServiceLocked(caller, token, service, 15994 resolvedType, connection, flags, callingPackage, userId); 15995 } 15996 } 15997 unbindService(IServiceConnection connection)15998 public boolean unbindService(IServiceConnection connection) { 15999 synchronized (this) { 16000 return mServices.unbindServiceLocked(connection); 16001 } 16002 } 16003 publishService(IBinder token, Intent intent, IBinder service)16004 public void publishService(IBinder token, Intent intent, IBinder service) { 16005 // Refuse possible leaked file descriptors 16006 if (intent != null && intent.hasFileDescriptors() == true) { 16007 throw new IllegalArgumentException("File descriptors passed in Intent"); 16008 } 16009 16010 synchronized(this) { 16011 if (!(token instanceof ServiceRecord)) { 16012 throw new IllegalArgumentException("Invalid service token"); 16013 } 16014 mServices.publishServiceLocked((ServiceRecord)token, intent, service); 16015 } 16016 } 16017 unbindFinished(IBinder token, Intent intent, boolean doRebind)16018 public void unbindFinished(IBinder token, Intent intent, boolean doRebind) { 16019 // Refuse possible leaked file descriptors 16020 if (intent != null && intent.hasFileDescriptors() == true) { 16021 throw new IllegalArgumentException("File descriptors passed in Intent"); 16022 } 16023 16024 synchronized(this) { 16025 mServices.unbindFinishedLocked((ServiceRecord)token, intent, doRebind); 16026 } 16027 } 16028 serviceDoneExecuting(IBinder token, int type, int startId, int res)16029 public void serviceDoneExecuting(IBinder token, int type, int startId, int res) { 16030 synchronized(this) { 16031 if (!(token instanceof ServiceRecord)) { 16032 Slog.e(TAG, "serviceDoneExecuting: Invalid service token=" + token); 16033 throw new IllegalArgumentException("Invalid service token"); 16034 } 16035 mServices.serviceDoneExecutingLocked((ServiceRecord)token, type, startId, res); 16036 } 16037 } 16038 16039 // ========================================================= 16040 // BACKUP AND RESTORE 16041 // ========================================================= 16042 16043 // Cause the target app to be launched if necessary and its backup agent 16044 // instantiated. The backup agent will invoke backupAgentCreated() on the 16045 // activity manager to announce its creation. bindBackupAgent(String packageName, int backupMode, int userId)16046 public boolean bindBackupAgent(String packageName, int backupMode, int userId) { 16047 if (DEBUG_BACKUP) Slog.v(TAG, "bindBackupAgent: app=" + packageName + " mode=" + backupMode); 16048 enforceCallingPermission("android.permission.CONFIRM_FULL_BACKUP", "bindBackupAgent"); 16049 16050 IPackageManager pm = AppGlobals.getPackageManager(); 16051 ApplicationInfo app = null; 16052 try { 16053 app = pm.getApplicationInfo(packageName, 0, userId); 16054 } catch (RemoteException e) { 16055 // can't happen; package manager is process-local 16056 } 16057 if (app == null) { 16058 Slog.w(TAG, "Unable to bind backup agent for " + packageName); 16059 return false; 16060 } 16061 16062 synchronized(this) { 16063 // !!! TODO: currently no check here that we're already bound 16064 BatteryStatsImpl.Uid.Pkg.Serv ss = null; 16065 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 16066 synchronized (stats) { 16067 ss = stats.getServiceStatsLocked(app.uid, app.packageName, app.name); 16068 } 16069 16070 // Backup agent is now in use, its package can't be stopped. 16071 try { 16072 AppGlobals.getPackageManager().setPackageStoppedState( 16073 app.packageName, false, UserHandle.getUserId(app.uid)); 16074 } catch (RemoteException e) { 16075 } catch (IllegalArgumentException e) { 16076 Slog.w(TAG, "Failed trying to unstop package " 16077 + app.packageName + ": " + e); 16078 } 16079 16080 BackupRecord r = new BackupRecord(ss, app, backupMode); 16081 ComponentName hostingName = (backupMode == IApplicationThread.BACKUP_MODE_INCREMENTAL) 16082 ? new ComponentName(app.packageName, app.backupAgentName) 16083 : new ComponentName("android", "FullBackupAgent"); 16084 // startProcessLocked() returns existing proc's record if it's already running 16085 ProcessRecord proc = startProcessLocked(app.processName, app, 16086 false, 0, "backup", hostingName, false, false, false); 16087 if (proc == null) { 16088 Slog.e(TAG, "Unable to start backup agent process " + r); 16089 return false; 16090 } 16091 16092 r.app = proc; 16093 mBackupTarget = r; 16094 mBackupAppName = app.packageName; 16095 16096 // Try not to kill the process during backup 16097 updateOomAdjLocked(proc); 16098 16099 // If the process is already attached, schedule the creation of the backup agent now. 16100 // If it is not yet live, this will be done when it attaches to the framework. 16101 if (proc.thread != null) { 16102 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc already running: " + proc); 16103 try { 16104 proc.thread.scheduleCreateBackupAgent(app, 16105 compatibilityInfoForPackageLocked(app), backupMode); 16106 } catch (RemoteException e) { 16107 // Will time out on the backup manager side 16108 } 16109 } else { 16110 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "Agent proc not running, waiting for attach"); 16111 } 16112 // Invariants: at this point, the target app process exists and the application 16113 // is either already running or in the process of coming up. mBackupTarget and 16114 // mBackupAppName describe the app, so that when it binds back to the AM we 16115 // know that it's scheduled for a backup-agent operation. 16116 } 16117 16118 return true; 16119 } 16120 16121 @Override clearPendingBackup()16122 public void clearPendingBackup() { 16123 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "clearPendingBackup"); 16124 enforceCallingPermission("android.permission.BACKUP", "clearPendingBackup"); 16125 16126 synchronized (this) { 16127 mBackupTarget = null; 16128 mBackupAppName = null; 16129 } 16130 } 16131 16132 // A backup agent has just come up backupAgentCreated(String agentPackageName, IBinder agent)16133 public void backupAgentCreated(String agentPackageName, IBinder agent) { 16134 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "backupAgentCreated: " + agentPackageName 16135 + " = " + agent); 16136 16137 synchronized(this) { 16138 if (!agentPackageName.equals(mBackupAppName)) { 16139 Slog.e(TAG, "Backup agent created for " + agentPackageName + " but not requested!"); 16140 return; 16141 } 16142 } 16143 16144 long oldIdent = Binder.clearCallingIdentity(); 16145 try { 16146 IBackupManager bm = IBackupManager.Stub.asInterface( 16147 ServiceManager.getService(Context.BACKUP_SERVICE)); 16148 bm.agentConnected(agentPackageName, agent); 16149 } catch (RemoteException e) { 16150 // can't happen; the backup manager service is local 16151 } catch (Exception e) { 16152 Slog.w(TAG, "Exception trying to deliver BackupAgent binding: "); 16153 e.printStackTrace(); 16154 } finally { 16155 Binder.restoreCallingIdentity(oldIdent); 16156 } 16157 } 16158 16159 // done with this agent unbindBackupAgent(ApplicationInfo appInfo)16160 public void unbindBackupAgent(ApplicationInfo appInfo) { 16161 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "unbindBackupAgent: " + appInfo); 16162 if (appInfo == null) { 16163 Slog.w(TAG, "unbind backup agent for null app"); 16164 return; 16165 } 16166 16167 synchronized(this) { 16168 try { 16169 if (mBackupAppName == null) { 16170 Slog.w(TAG, "Unbinding backup agent with no active backup"); 16171 return; 16172 } 16173 16174 if (!mBackupAppName.equals(appInfo.packageName)) { 16175 Slog.e(TAG, "Unbind of " + appInfo + " but is not the current backup target"); 16176 return; 16177 } 16178 16179 // Not backing this app up any more; reset its OOM adjustment 16180 final ProcessRecord proc = mBackupTarget.app; 16181 updateOomAdjLocked(proc); 16182 16183 // If the app crashed during backup, 'thread' will be null here 16184 if (proc.thread != null) { 16185 try { 16186 proc.thread.scheduleDestroyBackupAgent(appInfo, 16187 compatibilityInfoForPackageLocked(appInfo)); 16188 } catch (Exception e) { 16189 Slog.e(TAG, "Exception when unbinding backup agent:"); 16190 e.printStackTrace(); 16191 } 16192 } 16193 } finally { 16194 mBackupTarget = null; 16195 mBackupAppName = null; 16196 } 16197 } 16198 } 16199 // ========================================================= 16200 // BROADCASTS 16201 // ========================================================= 16202 isPendingBroadcastProcessLocked(int pid)16203 boolean isPendingBroadcastProcessLocked(int pid) { 16204 return mFgBroadcastQueue.isPendingBroadcastProcessLocked(pid) 16205 || mBgBroadcastQueue.isPendingBroadcastProcessLocked(pid); 16206 } 16207 skipPendingBroadcastLocked(int pid)16208 void skipPendingBroadcastLocked(int pid) { 16209 Slog.w(TAG, "Unattached app died before broadcast acknowledged, skipping"); 16210 for (BroadcastQueue queue : mBroadcastQueues) { 16211 queue.skipPendingBroadcastLocked(pid); 16212 } 16213 } 16214 16215 // The app just attached; send any pending broadcasts that it should receive sendPendingBroadcastsLocked(ProcessRecord app)16216 boolean sendPendingBroadcastsLocked(ProcessRecord app) { 16217 boolean didSomething = false; 16218 for (BroadcastQueue queue : mBroadcastQueues) { 16219 didSomething |= queue.sendPendingBroadcastsLocked(app); 16220 } 16221 return didSomething; 16222 } 16223 registerReceiver(IApplicationThread caller, String callerPackage, IIntentReceiver receiver, IntentFilter filter, String permission, int userId)16224 public Intent registerReceiver(IApplicationThread caller, String callerPackage, 16225 IIntentReceiver receiver, IntentFilter filter, String permission, int userId) { 16226 enforceNotIsolatedCaller("registerReceiver"); 16227 ArrayList<Intent> stickyIntents = null; 16228 ProcessRecord callerApp = null; 16229 int callingUid; 16230 int callingPid; 16231 synchronized(this) { 16232 if (caller != null) { 16233 callerApp = getRecordForAppLocked(caller); 16234 if (callerApp == null) { 16235 throw new SecurityException( 16236 "Unable to find app for caller " + caller 16237 + " (pid=" + Binder.getCallingPid() 16238 + ") when registering receiver " + receiver); 16239 } 16240 if (callerApp.info.uid != Process.SYSTEM_UID && 16241 !callerApp.pkgList.containsKey(callerPackage) && 16242 !"android".equals(callerPackage)) { 16243 throw new SecurityException("Given caller package " + callerPackage 16244 + " is not running in process " + callerApp); 16245 } 16246 callingUid = callerApp.info.uid; 16247 callingPid = callerApp.pid; 16248 } else { 16249 callerPackage = null; 16250 callingUid = Binder.getCallingUid(); 16251 callingPid = Binder.getCallingPid(); 16252 } 16253 16254 userId = handleIncomingUser(callingPid, callingUid, userId, 16255 true, ALLOW_FULL_ONLY, "registerReceiver", callerPackage); 16256 16257 Iterator<String> actions = filter.actionsIterator(); 16258 if (actions == null) { 16259 ArrayList<String> noAction = new ArrayList<String>(1); 16260 noAction.add(null); 16261 actions = noAction.iterator(); 16262 } 16263 16264 // Collect stickies of users 16265 int[] userIds = { UserHandle.USER_ALL, UserHandle.getUserId(callingUid) }; 16266 while (actions.hasNext()) { 16267 String action = actions.next(); 16268 for (int id : userIds) { 16269 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(id); 16270 if (stickies != null) { 16271 ArrayList<Intent> intents = stickies.get(action); 16272 if (intents != null) { 16273 if (stickyIntents == null) { 16274 stickyIntents = new ArrayList<Intent>(); 16275 } 16276 stickyIntents.addAll(intents); 16277 } 16278 } 16279 } 16280 } 16281 } 16282 16283 ArrayList<Intent> allSticky = null; 16284 if (stickyIntents != null) { 16285 final ContentResolver resolver = mContext.getContentResolver(); 16286 // Look for any matching sticky broadcasts... 16287 for (int i = 0, N = stickyIntents.size(); i < N; i++) { 16288 Intent intent = stickyIntents.get(i); 16289 // If intent has scheme "content", it will need to acccess 16290 // provider that needs to lock mProviderMap in ActivityThread 16291 // and also it may need to wait application response, so we 16292 // cannot lock ActivityManagerService here. 16293 if (filter.match(resolver, intent, true, TAG) >= 0) { 16294 if (allSticky == null) { 16295 allSticky = new ArrayList<Intent>(); 16296 } 16297 allSticky.add(intent); 16298 } 16299 } 16300 } 16301 16302 // The first sticky in the list is returned directly back to the client. 16303 Intent sticky = allSticky != null ? allSticky.get(0) : null; 16304 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Register receiver " + filter + ": " + sticky); 16305 if (receiver == null) { 16306 return sticky; 16307 } 16308 16309 synchronized (this) { 16310 if (callerApp != null && (callerApp.thread == null 16311 || callerApp.thread.asBinder() != caller.asBinder())) { 16312 // Original caller already died 16313 return null; 16314 } 16315 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 16316 if (rl == null) { 16317 rl = new ReceiverList(this, callerApp, callingPid, callingUid, 16318 userId, receiver); 16319 if (rl.app != null) { 16320 rl.app.receivers.add(rl); 16321 } else { 16322 try { 16323 receiver.asBinder().linkToDeath(rl, 0); 16324 } catch (RemoteException e) { 16325 return sticky; 16326 } 16327 rl.linkedToDeath = true; 16328 } 16329 mRegisteredReceivers.put(receiver.asBinder(), rl); 16330 } else if (rl.uid != callingUid) { 16331 throw new IllegalArgumentException( 16332 "Receiver requested to register for uid " + callingUid 16333 + " was previously registered for uid " + rl.uid); 16334 } else if (rl.pid != callingPid) { 16335 throw new IllegalArgumentException( 16336 "Receiver requested to register for pid " + callingPid 16337 + " was previously registered for pid " + rl.pid); 16338 } else if (rl.userId != userId) { 16339 throw new IllegalArgumentException( 16340 "Receiver requested to register for user " + userId 16341 + " was previously registered for user " + rl.userId); 16342 } 16343 BroadcastFilter bf = new BroadcastFilter(filter, rl, callerPackage, 16344 permission, callingUid, userId); 16345 rl.add(bf); 16346 if (!bf.debugCheck()) { 16347 Slog.w(TAG, "==> For Dynamic broadcast"); 16348 } 16349 mReceiverResolver.addFilter(bf); 16350 16351 // Enqueue broadcasts for all existing stickies that match 16352 // this filter. 16353 if (allSticky != null) { 16354 ArrayList receivers = new ArrayList(); 16355 receivers.add(bf); 16356 16357 final int stickyCount = allSticky.size(); 16358 for (int i = 0; i < stickyCount; i++) { 16359 Intent intent = allSticky.get(i); 16360 BroadcastQueue queue = broadcastQueueForIntent(intent); 16361 BroadcastRecord r = new BroadcastRecord(queue, intent, null, 16362 null, -1, -1, null, null, AppOpsManager.OP_NONE, null, receivers, 16363 null, 0, null, null, false, true, true, -1); 16364 queue.enqueueParallelBroadcastLocked(r); 16365 queue.scheduleBroadcastsLocked(); 16366 } 16367 } 16368 16369 return sticky; 16370 } 16371 } 16372 unregisterReceiver(IIntentReceiver receiver)16373 public void unregisterReceiver(IIntentReceiver receiver) { 16374 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Unregister receiver: " + receiver); 16375 16376 final long origId = Binder.clearCallingIdentity(); 16377 try { 16378 boolean doTrim = false; 16379 16380 synchronized(this) { 16381 ReceiverList rl = mRegisteredReceivers.get(receiver.asBinder()); 16382 if (rl != null) { 16383 final BroadcastRecord r = rl.curBroadcast; 16384 if (r != null && r == r.queue.getMatchingOrderedReceiver(r)) { 16385 final boolean doNext = r.queue.finishReceiverLocked( 16386 r, r.resultCode, r.resultData, r.resultExtras, 16387 r.resultAbort, false); 16388 if (doNext) { 16389 doTrim = true; 16390 r.queue.processNextBroadcast(false); 16391 } 16392 } 16393 16394 if (rl.app != null) { 16395 rl.app.receivers.remove(rl); 16396 } 16397 removeReceiverLocked(rl); 16398 if (rl.linkedToDeath) { 16399 rl.linkedToDeath = false; 16400 rl.receiver.asBinder().unlinkToDeath(rl, 0); 16401 } 16402 } 16403 } 16404 16405 // If we actually concluded any broadcasts, we might now be able 16406 // to trim the recipients' apps from our working set 16407 if (doTrim) { 16408 trimApplications(); 16409 return; 16410 } 16411 16412 } finally { 16413 Binder.restoreCallingIdentity(origId); 16414 } 16415 } 16416 removeReceiverLocked(ReceiverList rl)16417 void removeReceiverLocked(ReceiverList rl) { 16418 mRegisteredReceivers.remove(rl.receiver.asBinder()); 16419 for (int i = rl.size() - 1; i >= 0; i--) { 16420 mReceiverResolver.removeFilter(rl.get(i)); 16421 } 16422 } 16423 sendPackageBroadcastLocked(int cmd, String[] packages, int userId)16424 private final void sendPackageBroadcastLocked(int cmd, String[] packages, int userId) { 16425 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 16426 ProcessRecord r = mLruProcesses.get(i); 16427 if (r.thread != null && (userId == UserHandle.USER_ALL || r.userId == userId)) { 16428 try { 16429 r.thread.dispatchPackageBroadcast(cmd, packages); 16430 } catch (RemoteException ex) { 16431 } 16432 } 16433 } 16434 } 16435 collectReceiverComponents(Intent intent, String resolvedType, int callingUid, int[] users)16436 private List<ResolveInfo> collectReceiverComponents(Intent intent, String resolvedType, 16437 int callingUid, int[] users) { 16438 List<ResolveInfo> receivers = null; 16439 try { 16440 HashSet<ComponentName> singleUserReceivers = null; 16441 boolean scannedFirstReceivers = false; 16442 for (int user : users) { 16443 // Skip users that have Shell restrictions 16444 if (callingUid == Process.SHELL_UID 16445 && getUserManagerLocked().hasUserRestriction( 16446 UserManager.DISALLOW_DEBUGGING_FEATURES, user)) { 16447 continue; 16448 } 16449 List<ResolveInfo> newReceivers = AppGlobals.getPackageManager() 16450 .queryIntentReceivers(intent, resolvedType, STOCK_PM_FLAGS, user); 16451 if (user != UserHandle.USER_OWNER && newReceivers != null) { 16452 // If this is not the primary user, we need to check for 16453 // any receivers that should be filtered out. 16454 for (int i=0; i<newReceivers.size(); i++) { 16455 ResolveInfo ri = newReceivers.get(i); 16456 if ((ri.activityInfo.flags&ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) { 16457 newReceivers.remove(i); 16458 i--; 16459 } 16460 } 16461 } 16462 if (newReceivers != null && newReceivers.size() == 0) { 16463 newReceivers = null; 16464 } 16465 if (receivers == null) { 16466 receivers = newReceivers; 16467 } else if (newReceivers != null) { 16468 // We need to concatenate the additional receivers 16469 // found with what we have do far. This would be easy, 16470 // but we also need to de-dup any receivers that are 16471 // singleUser. 16472 if (!scannedFirstReceivers) { 16473 // Collect any single user receivers we had already retrieved. 16474 scannedFirstReceivers = true; 16475 for (int i=0; i<receivers.size(); i++) { 16476 ResolveInfo ri = receivers.get(i); 16477 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 16478 ComponentName cn = new ComponentName( 16479 ri.activityInfo.packageName, ri.activityInfo.name); 16480 if (singleUserReceivers == null) { 16481 singleUserReceivers = new HashSet<ComponentName>(); 16482 } 16483 singleUserReceivers.add(cn); 16484 } 16485 } 16486 } 16487 // Add the new results to the existing results, tracking 16488 // and de-dupping single user receivers. 16489 for (int i=0; i<newReceivers.size(); i++) { 16490 ResolveInfo ri = newReceivers.get(i); 16491 if ((ri.activityInfo.flags&ActivityInfo.FLAG_SINGLE_USER) != 0) { 16492 ComponentName cn = new ComponentName( 16493 ri.activityInfo.packageName, ri.activityInfo.name); 16494 if (singleUserReceivers == null) { 16495 singleUserReceivers = new HashSet<ComponentName>(); 16496 } 16497 if (!singleUserReceivers.contains(cn)) { 16498 singleUserReceivers.add(cn); 16499 receivers.add(ri); 16500 } 16501 } else { 16502 receivers.add(ri); 16503 } 16504 } 16505 } 16506 } 16507 } catch (RemoteException ex) { 16508 // pm is in same process, this will never happen. 16509 } 16510 return receivers; 16511 } 16512 broadcastIntentLocked(ProcessRecord callerApp, String callerPackage, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle options, boolean ordered, boolean sticky, int callingPid, int callingUid, int userId)16513 private final int broadcastIntentLocked(ProcessRecord callerApp, 16514 String callerPackage, Intent intent, String resolvedType, 16515 IIntentReceiver resultTo, int resultCode, String resultData, 16516 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle options, 16517 boolean ordered, boolean sticky, int callingPid, int callingUid, int userId) { 16518 intent = new Intent(intent); 16519 16520 // By default broadcasts do not go to stopped apps. 16521 intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES); 16522 16523 // If we have not finished booting, don't allow this to launch new processes. 16524 if (!mProcessesReady && (intent.getFlags()&Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) { 16525 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 16526 } 16527 16528 if (DEBUG_BROADCAST_LIGHT) Slog.v(TAG_BROADCAST, 16529 (sticky ? "Broadcast sticky: ": "Broadcast: ") + intent 16530 + " ordered=" + ordered + " userid=" + userId); 16531 if ((resultTo != null) && !ordered) { 16532 Slog.w(TAG, "Broadcast " + intent + " not ordered but result callback requested!"); 16533 } 16534 16535 userId = handleIncomingUser(callingPid, callingUid, userId, 16536 true, ALLOW_NON_FULL, "broadcast", callerPackage); 16537 16538 // Make sure that the user who is receiving this broadcast is running. 16539 // If not, we will just skip it. Make an exception for shutdown broadcasts 16540 // and upgrade steps. 16541 16542 if (userId != UserHandle.USER_ALL && !isUserRunningLocked(userId, false)) { 16543 if ((callingUid != Process.SYSTEM_UID 16544 || (intent.getFlags() & Intent.FLAG_RECEIVER_BOOT_UPGRADE) == 0) 16545 && !Intent.ACTION_SHUTDOWN.equals(intent.getAction())) { 16546 Slog.w(TAG, "Skipping broadcast of " + intent 16547 + ": user " + userId + " is stopped"); 16548 return ActivityManager.BROADCAST_FAILED_USER_STOPPED; 16549 } 16550 } 16551 16552 BroadcastOptions brOptions = null; 16553 if (options != null) { 16554 brOptions = new BroadcastOptions(options); 16555 if (brOptions.getTemporaryAppWhitelistDuration() > 0) { 16556 // See if the caller is allowed to do this. Note we are checking against 16557 // the actual real caller (not whoever provided the operation as say a 16558 // PendingIntent), because that who is actually supplied the arguments. 16559 if (checkComponentPermission( 16560 android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST, 16561 Binder.getCallingPid(), Binder.getCallingUid(), -1, true) 16562 != PackageManager.PERMISSION_GRANTED) { 16563 String msg = "Permission Denial: " + intent.getAction() 16564 + " broadcast from " + callerPackage + " (pid=" + callingPid 16565 + ", uid=" + callingUid + ")" 16566 + " requires " 16567 + android.Manifest.permission.CHANGE_DEVICE_IDLE_TEMP_WHITELIST; 16568 Slog.w(TAG, msg); 16569 throw new SecurityException(msg); 16570 } 16571 } 16572 } 16573 16574 /* 16575 * Prevent non-system code (defined here to be non-persistent 16576 * processes) from sending protected broadcasts. 16577 */ 16578 int callingAppId = UserHandle.getAppId(callingUid); 16579 if (callingAppId == Process.SYSTEM_UID || callingAppId == Process.PHONE_UID 16580 || callingAppId == Process.SHELL_UID || callingAppId == Process.BLUETOOTH_UID 16581 || callingAppId == Process.NFC_UID || callingUid == 0) { 16582 // Always okay. 16583 } else if (callerApp == null || !callerApp.persistent) { 16584 try { 16585 if (AppGlobals.getPackageManager().isProtectedBroadcast( 16586 intent.getAction())) { 16587 String msg = "Permission Denial: not allowed to send broadcast " 16588 + intent.getAction() + " from pid=" 16589 + callingPid + ", uid=" + callingUid; 16590 Slog.w(TAG, msg); 16591 throw new SecurityException(msg); 16592 } else if (AppWidgetManager.ACTION_APPWIDGET_CONFIGURE.equals(intent.getAction())) { 16593 // Special case for compatibility: we don't want apps to send this, 16594 // but historically it has not been protected and apps may be using it 16595 // to poke their own app widget. So, instead of making it protected, 16596 // just limit it to the caller. 16597 if (callerApp == null) { 16598 String msg = "Permission Denial: not allowed to send broadcast " 16599 + intent.getAction() + " from unknown caller."; 16600 Slog.w(TAG, msg); 16601 throw new SecurityException(msg); 16602 } else if (intent.getComponent() != null) { 16603 // They are good enough to send to an explicit component... verify 16604 // it is being sent to the calling app. 16605 if (!intent.getComponent().getPackageName().equals( 16606 callerApp.info.packageName)) { 16607 String msg = "Permission Denial: not allowed to send broadcast " 16608 + intent.getAction() + " to " 16609 + intent.getComponent().getPackageName() + " from " 16610 + callerApp.info.packageName; 16611 Slog.w(TAG, msg); 16612 throw new SecurityException(msg); 16613 } 16614 } else { 16615 // Limit broadcast to their own package. 16616 intent.setPackage(callerApp.info.packageName); 16617 } 16618 } 16619 } catch (RemoteException e) { 16620 Slog.w(TAG, "Remote exception", e); 16621 return ActivityManager.BROADCAST_SUCCESS; 16622 } 16623 } 16624 16625 final String action = intent.getAction(); 16626 if (action != null) { 16627 switch (action) { 16628 case Intent.ACTION_UID_REMOVED: 16629 case Intent.ACTION_PACKAGE_REMOVED: 16630 case Intent.ACTION_PACKAGE_CHANGED: 16631 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 16632 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 16633 // Handle special intents: if this broadcast is from the package 16634 // manager about a package being removed, we need to remove all of 16635 // its activities from the history stack. 16636 if (checkComponentPermission( 16637 android.Manifest.permission.BROADCAST_PACKAGE_REMOVED, 16638 callingPid, callingUid, -1, true) 16639 != PackageManager.PERMISSION_GRANTED) { 16640 String msg = "Permission Denial: " + intent.getAction() 16641 + " broadcast from " + callerPackage + " (pid=" + callingPid 16642 + ", uid=" + callingUid + ")" 16643 + " requires " 16644 + android.Manifest.permission.BROADCAST_PACKAGE_REMOVED; 16645 Slog.w(TAG, msg); 16646 throw new SecurityException(msg); 16647 } 16648 switch (action) { 16649 case Intent.ACTION_UID_REMOVED: 16650 final Bundle intentExtras = intent.getExtras(); 16651 final int uid = intentExtras != null 16652 ? intentExtras.getInt(Intent.EXTRA_UID) : -1; 16653 if (uid >= 0) { 16654 mBatteryStatsService.removeUid(uid); 16655 mAppOpsService.uidRemoved(uid); 16656 } 16657 break; 16658 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE: 16659 // If resources are unavailable just force stop all those packages 16660 // and flush the attribute cache as well. 16661 String list[] = 16662 intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 16663 if (list != null && list.length > 0) { 16664 for (int i = 0; i < list.length; i++) { 16665 forceStopPackageLocked(list[i], -1, false, true, true, 16666 false, false, userId, "storage unmount"); 16667 } 16668 mRecentTasks.cleanupLocked(UserHandle.USER_ALL); 16669 sendPackageBroadcastLocked( 16670 IApplicationThread.EXTERNAL_STORAGE_UNAVAILABLE, list, 16671 userId); 16672 } 16673 break; 16674 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE: 16675 mRecentTasks.cleanupLocked(UserHandle.USER_ALL); 16676 break; 16677 case Intent.ACTION_PACKAGE_REMOVED: 16678 case Intent.ACTION_PACKAGE_CHANGED: 16679 Uri data = intent.getData(); 16680 String ssp; 16681 if (data != null && (ssp=data.getSchemeSpecificPart()) != null) { 16682 boolean removed = Intent.ACTION_PACKAGE_REMOVED.equals(action); 16683 boolean fullUninstall = removed && 16684 !intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 16685 final boolean killProcess = 16686 !intent.getBooleanExtra(Intent.EXTRA_DONT_KILL_APP, false); 16687 if (killProcess) { 16688 forceStopPackageLocked(ssp, UserHandle.getAppId( 16689 intent.getIntExtra(Intent.EXTRA_UID, -1)), 16690 false, true, true, false, fullUninstall, userId, 16691 removed ? "pkg removed" : "pkg changed"); 16692 } 16693 if (removed) { 16694 sendPackageBroadcastLocked(IApplicationThread.PACKAGE_REMOVED, 16695 new String[] {ssp}, userId); 16696 if (fullUninstall) { 16697 mAppOpsService.packageRemoved( 16698 intent.getIntExtra(Intent.EXTRA_UID, -1), ssp); 16699 16700 // Remove all permissions granted from/to this package 16701 removeUriPermissionsForPackageLocked(ssp, userId, true); 16702 16703 removeTasksByPackageNameLocked(ssp, userId); 16704 mBatteryStatsService.notePackageUninstalled(ssp); 16705 } 16706 } else { 16707 cleanupDisabledPackageComponentsLocked(ssp, userId, killProcess, 16708 intent.getStringArrayExtra( 16709 Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST)); 16710 } 16711 } 16712 break; 16713 } 16714 break; 16715 case Intent.ACTION_PACKAGE_ADDED: 16716 // Special case for adding a package: by default turn on compatibility mode. 16717 Uri data = intent.getData(); 16718 String ssp; 16719 if (data != null && (ssp = data.getSchemeSpecificPart()) != null) { 16720 final boolean replacing = 16721 intent.getBooleanExtra(Intent.EXTRA_REPLACING, false); 16722 mCompatModePackages.handlePackageAddedLocked(ssp, replacing); 16723 16724 try { 16725 ApplicationInfo ai = AppGlobals.getPackageManager(). 16726 getApplicationInfo(ssp, 0, 0); 16727 mBatteryStatsService.notePackageInstalled(ssp, 16728 ai != null ? ai.versionCode : 0); 16729 } catch (RemoteException e) { 16730 } 16731 } 16732 break; 16733 case Intent.ACTION_TIMEZONE_CHANGED: 16734 // If this is the time zone changed action, queue up a message that will reset 16735 // the timezone of all currently running processes. This message will get 16736 // queued up before the broadcast happens. 16737 mHandler.sendEmptyMessage(UPDATE_TIME_ZONE); 16738 break; 16739 case Intent.ACTION_TIME_CHANGED: 16740 // If the user set the time, let all running processes know. 16741 final int is24Hour = 16742 intent.getBooleanExtra(Intent.EXTRA_TIME_PREF_24_HOUR_FORMAT, false) ? 1 16743 : 0; 16744 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_TIME, is24Hour, 0)); 16745 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 16746 synchronized (stats) { 16747 stats.noteCurrentTimeChangedLocked(); 16748 } 16749 break; 16750 case Intent.ACTION_CLEAR_DNS_CACHE: 16751 mHandler.sendEmptyMessage(CLEAR_DNS_CACHE_MSG); 16752 break; 16753 case Proxy.PROXY_CHANGE_ACTION: 16754 ProxyInfo proxy = intent.getParcelableExtra(Proxy.EXTRA_PROXY_INFO); 16755 mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG, proxy)); 16756 break; 16757 } 16758 } 16759 16760 // Add to the sticky list if requested. 16761 if (sticky) { 16762 if (checkPermission(android.Manifest.permission.BROADCAST_STICKY, 16763 callingPid, callingUid) 16764 != PackageManager.PERMISSION_GRANTED) { 16765 String msg = "Permission Denial: broadcastIntent() requesting a sticky broadcast from pid=" 16766 + callingPid + ", uid=" + callingUid 16767 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 16768 Slog.w(TAG, msg); 16769 throw new SecurityException(msg); 16770 } 16771 if (requiredPermissions != null && requiredPermissions.length > 0) { 16772 Slog.w(TAG, "Can't broadcast sticky intent " + intent 16773 + " and enforce permissions " + Arrays.toString(requiredPermissions)); 16774 return ActivityManager.BROADCAST_STICKY_CANT_HAVE_PERMISSION; 16775 } 16776 if (intent.getComponent() != null) { 16777 throw new SecurityException( 16778 "Sticky broadcasts can't target a specific component"); 16779 } 16780 // We use userId directly here, since the "all" target is maintained 16781 // as a separate set of sticky broadcasts. 16782 if (userId != UserHandle.USER_ALL) { 16783 // But first, if this is not a broadcast to all users, then 16784 // make sure it doesn't conflict with an existing broadcast to 16785 // all users. 16786 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get( 16787 UserHandle.USER_ALL); 16788 if (stickies != null) { 16789 ArrayList<Intent> list = stickies.get(intent.getAction()); 16790 if (list != null) { 16791 int N = list.size(); 16792 int i; 16793 for (i=0; i<N; i++) { 16794 if (intent.filterEquals(list.get(i))) { 16795 throw new IllegalArgumentException( 16796 "Sticky broadcast " + intent + " for user " 16797 + userId + " conflicts with existing global broadcast"); 16798 } 16799 } 16800 } 16801 } 16802 } 16803 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 16804 if (stickies == null) { 16805 stickies = new ArrayMap<>(); 16806 mStickyBroadcasts.put(userId, stickies); 16807 } 16808 ArrayList<Intent> list = stickies.get(intent.getAction()); 16809 if (list == null) { 16810 list = new ArrayList<>(); 16811 stickies.put(intent.getAction(), list); 16812 } 16813 final int stickiesCount = list.size(); 16814 int i; 16815 for (i = 0; i < stickiesCount; i++) { 16816 if (intent.filterEquals(list.get(i))) { 16817 // This sticky already exists, replace it. 16818 list.set(i, new Intent(intent)); 16819 break; 16820 } 16821 } 16822 if (i >= stickiesCount) { 16823 list.add(new Intent(intent)); 16824 } 16825 } 16826 16827 int[] users; 16828 if (userId == UserHandle.USER_ALL) { 16829 // Caller wants broadcast to go to all started users. 16830 users = mStartedUserArray; 16831 } else { 16832 // Caller wants broadcast to go to one specific user. 16833 users = new int[] {userId}; 16834 } 16835 16836 // Figure out who all will receive this broadcast. 16837 List receivers = null; 16838 List<BroadcastFilter> registeredReceivers = null; 16839 // Need to resolve the intent to interested receivers... 16840 if ((intent.getFlags()&Intent.FLAG_RECEIVER_REGISTERED_ONLY) 16841 == 0) { 16842 receivers = collectReceiverComponents(intent, resolvedType, callingUid, users); 16843 } 16844 if (intent.getComponent() == null) { 16845 if (userId == UserHandle.USER_ALL && callingUid == Process.SHELL_UID) { 16846 // Query one target user at a time, excluding shell-restricted users 16847 UserManagerService ums = getUserManagerLocked(); 16848 for (int i = 0; i < users.length; i++) { 16849 if (ums.hasUserRestriction( 16850 UserManager.DISALLOW_DEBUGGING_FEATURES, users[i])) { 16851 continue; 16852 } 16853 List<BroadcastFilter> registeredReceiversForUser = 16854 mReceiverResolver.queryIntent(intent, 16855 resolvedType, false, users[i]); 16856 if (registeredReceivers == null) { 16857 registeredReceivers = registeredReceiversForUser; 16858 } else if (registeredReceiversForUser != null) { 16859 registeredReceivers.addAll(registeredReceiversForUser); 16860 } 16861 } 16862 } else { 16863 registeredReceivers = mReceiverResolver.queryIntent(intent, 16864 resolvedType, false, userId); 16865 } 16866 } 16867 16868 final boolean replacePending = 16869 (intent.getFlags()&Intent.FLAG_RECEIVER_REPLACE_PENDING) != 0; 16870 16871 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueing broadcast: " + intent.getAction() 16872 + " replacePending=" + replacePending); 16873 16874 int NR = registeredReceivers != null ? registeredReceivers.size() : 0; 16875 if (!ordered && NR > 0) { 16876 // If we are not serializing this broadcast, then send the 16877 // registered receivers separately so they don't wait for the 16878 // components to be launched. 16879 final BroadcastQueue queue = broadcastQueueForIntent(intent); 16880 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 16881 callerPackage, callingPid, callingUid, resolvedType, requiredPermissions, 16882 appOp, brOptions, registeredReceivers, resultTo, resultCode, resultData, 16883 resultExtras, ordered, sticky, false, userId); 16884 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing parallel broadcast " + r); 16885 final boolean replaced = replacePending && queue.replaceParallelBroadcastLocked(r); 16886 if (!replaced) { 16887 queue.enqueueParallelBroadcastLocked(r); 16888 queue.scheduleBroadcastsLocked(); 16889 } 16890 registeredReceivers = null; 16891 NR = 0; 16892 } 16893 16894 // Merge into one list. 16895 int ir = 0; 16896 if (receivers != null) { 16897 // A special case for PACKAGE_ADDED: do not allow the package 16898 // being added to see this broadcast. This prevents them from 16899 // using this as a back door to get run as soon as they are 16900 // installed. Maybe in the future we want to have a special install 16901 // broadcast or such for apps, but we'd like to deliberately make 16902 // this decision. 16903 String skipPackages[] = null; 16904 if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction()) 16905 || Intent.ACTION_PACKAGE_RESTARTED.equals(intent.getAction()) 16906 || Intent.ACTION_PACKAGE_DATA_CLEARED.equals(intent.getAction())) { 16907 Uri data = intent.getData(); 16908 if (data != null) { 16909 String pkgName = data.getSchemeSpecificPart(); 16910 if (pkgName != null) { 16911 skipPackages = new String[] { pkgName }; 16912 } 16913 } 16914 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE.equals(intent.getAction())) { 16915 skipPackages = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST); 16916 } 16917 if (skipPackages != null && (skipPackages.length > 0)) { 16918 for (String skipPackage : skipPackages) { 16919 if (skipPackage != null) { 16920 int NT = receivers.size(); 16921 for (int it=0; it<NT; it++) { 16922 ResolveInfo curt = (ResolveInfo)receivers.get(it); 16923 if (curt.activityInfo.packageName.equals(skipPackage)) { 16924 receivers.remove(it); 16925 it--; 16926 NT--; 16927 } 16928 } 16929 } 16930 } 16931 } 16932 16933 int NT = receivers != null ? receivers.size() : 0; 16934 int it = 0; 16935 ResolveInfo curt = null; 16936 BroadcastFilter curr = null; 16937 while (it < NT && ir < NR) { 16938 if (curt == null) { 16939 curt = (ResolveInfo)receivers.get(it); 16940 } 16941 if (curr == null) { 16942 curr = registeredReceivers.get(ir); 16943 } 16944 if (curr.getPriority() >= curt.priority) { 16945 // Insert this broadcast record into the final list. 16946 receivers.add(it, curr); 16947 ir++; 16948 curr = null; 16949 it++; 16950 NT++; 16951 } else { 16952 // Skip to the next ResolveInfo in the final list. 16953 it++; 16954 curt = null; 16955 } 16956 } 16957 } 16958 while (ir < NR) { 16959 if (receivers == null) { 16960 receivers = new ArrayList(); 16961 } 16962 receivers.add(registeredReceivers.get(ir)); 16963 ir++; 16964 } 16965 16966 if ((receivers != null && receivers.size() > 0) 16967 || resultTo != null) { 16968 BroadcastQueue queue = broadcastQueueForIntent(intent); 16969 BroadcastRecord r = new BroadcastRecord(queue, intent, callerApp, 16970 callerPackage, callingPid, callingUid, resolvedType, 16971 requiredPermissions, appOp, brOptions, receivers, resultTo, resultCode, 16972 resultData, resultExtras, ordered, sticky, false, userId); 16973 16974 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Enqueueing ordered broadcast " + r 16975 + ": prev had " + queue.mOrderedBroadcasts.size()); 16976 if (DEBUG_BROADCAST) Slog.i(TAG_BROADCAST, 16977 "Enqueueing broadcast " + r.intent.getAction()); 16978 16979 boolean replaced = replacePending && queue.replaceOrderedBroadcastLocked(r); 16980 if (!replaced) { 16981 queue.enqueueOrderedBroadcastLocked(r); 16982 queue.scheduleBroadcastsLocked(); 16983 } 16984 } 16985 16986 return ActivityManager.BROADCAST_SUCCESS; 16987 } 16988 verifyBroadcastLocked(Intent intent)16989 final Intent verifyBroadcastLocked(Intent intent) { 16990 // Refuse possible leaked file descriptors 16991 if (intent != null && intent.hasFileDescriptors() == true) { 16992 throw new IllegalArgumentException("File descriptors passed in Intent"); 16993 } 16994 16995 int flags = intent.getFlags(); 16996 16997 if (!mProcessesReady) { 16998 // if the caller really truly claims to know what they're doing, go 16999 // ahead and allow the broadcast without launching any receivers 17000 if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT) != 0) { 17001 // This will be turned into a FLAG_RECEIVER_REGISTERED_ONLY later on if needed. 17002 } else if ((flags&Intent.FLAG_RECEIVER_REGISTERED_ONLY) == 0) { 17003 Slog.e(TAG, "Attempt to launch receivers of broadcast intent " + intent 17004 + " before boot completion"); 17005 throw new IllegalStateException("Cannot broadcast before boot completed"); 17006 } 17007 } 17008 17009 if ((flags&Intent.FLAG_RECEIVER_BOOT_UPGRADE) != 0) { 17010 throw new IllegalArgumentException( 17011 "Can't use FLAG_RECEIVER_BOOT_UPGRADE here"); 17012 } 17013 17014 return intent; 17015 } 17016 broadcastIntent(IApplicationThread caller, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle options, boolean serialized, boolean sticky, int userId)17017 public final int broadcastIntent(IApplicationThread caller, 17018 Intent intent, String resolvedType, IIntentReceiver resultTo, 17019 int resultCode, String resultData, Bundle resultExtras, 17020 String[] requiredPermissions, int appOp, Bundle options, 17021 boolean serialized, boolean sticky, int userId) { 17022 enforceNotIsolatedCaller("broadcastIntent"); 17023 synchronized(this) { 17024 intent = verifyBroadcastLocked(intent); 17025 17026 final ProcessRecord callerApp = getRecordForAppLocked(caller); 17027 final int callingPid = Binder.getCallingPid(); 17028 final int callingUid = Binder.getCallingUid(); 17029 final long origId = Binder.clearCallingIdentity(); 17030 int res = broadcastIntentLocked(callerApp, 17031 callerApp != null ? callerApp.info.packageName : null, 17032 intent, resolvedType, resultTo, resultCode, resultData, resultExtras, 17033 requiredPermissions, appOp, null, serialized, sticky, 17034 callingPid, callingUid, userId); 17035 Binder.restoreCallingIdentity(origId); 17036 return res; 17037 } 17038 } 17039 17040 broadcastIntentInPackage(String packageName, int uid, Intent intent, String resolvedType, IIntentReceiver resultTo, int resultCode, String resultData, Bundle resultExtras, String requiredPermission, Bundle options, boolean serialized, boolean sticky, int userId)17041 int broadcastIntentInPackage(String packageName, int uid, 17042 Intent intent, String resolvedType, IIntentReceiver resultTo, 17043 int resultCode, String resultData, Bundle resultExtras, 17044 String requiredPermission, Bundle options, boolean serialized, boolean sticky, 17045 int userId) { 17046 synchronized(this) { 17047 intent = verifyBroadcastLocked(intent); 17048 17049 final long origId = Binder.clearCallingIdentity(); 17050 String[] requiredPermissions = requiredPermission == null ? null 17051 : new String[] {requiredPermission}; 17052 int res = broadcastIntentLocked(null, packageName, intent, resolvedType, 17053 resultTo, resultCode, resultData, resultExtras, 17054 requiredPermissions, AppOpsManager.OP_NONE, options, serialized, 17055 sticky, -1, uid, userId); 17056 Binder.restoreCallingIdentity(origId); 17057 return res; 17058 } 17059 } 17060 unbroadcastIntent(IApplicationThread caller, Intent intent, int userId)17061 public final void unbroadcastIntent(IApplicationThread caller, Intent intent, int userId) { 17062 // Refuse possible leaked file descriptors 17063 if (intent != null && intent.hasFileDescriptors() == true) { 17064 throw new IllegalArgumentException("File descriptors passed in Intent"); 17065 } 17066 17067 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 17068 userId, true, ALLOW_NON_FULL, "removeStickyBroadcast", null); 17069 17070 synchronized(this) { 17071 if (checkCallingPermission(android.Manifest.permission.BROADCAST_STICKY) 17072 != PackageManager.PERMISSION_GRANTED) { 17073 String msg = "Permission Denial: unbroadcastIntent() from pid=" 17074 + Binder.getCallingPid() 17075 + ", uid=" + Binder.getCallingUid() 17076 + " requires " + android.Manifest.permission.BROADCAST_STICKY; 17077 Slog.w(TAG, msg); 17078 throw new SecurityException(msg); 17079 } 17080 ArrayMap<String, ArrayList<Intent>> stickies = mStickyBroadcasts.get(userId); 17081 if (stickies != null) { 17082 ArrayList<Intent> list = stickies.get(intent.getAction()); 17083 if (list != null) { 17084 int N = list.size(); 17085 int i; 17086 for (i=0; i<N; i++) { 17087 if (intent.filterEquals(list.get(i))) { 17088 list.remove(i); 17089 break; 17090 } 17091 } 17092 if (list.size() <= 0) { 17093 stickies.remove(intent.getAction()); 17094 } 17095 } 17096 if (stickies.size() <= 0) { 17097 mStickyBroadcasts.remove(userId); 17098 } 17099 } 17100 } 17101 } 17102 backgroundServicesFinishedLocked(int userId)17103 void backgroundServicesFinishedLocked(int userId) { 17104 for (BroadcastQueue queue : mBroadcastQueues) { 17105 queue.backgroundServicesFinishedLocked(userId); 17106 } 17107 } 17108 finishReceiver(IBinder who, int resultCode, String resultData, Bundle resultExtras, boolean resultAbort, int flags)17109 public void finishReceiver(IBinder who, int resultCode, String resultData, 17110 Bundle resultExtras, boolean resultAbort, int flags) { 17111 if (DEBUG_BROADCAST) Slog.v(TAG_BROADCAST, "Finish receiver: " + who); 17112 17113 // Refuse possible leaked file descriptors 17114 if (resultExtras != null && resultExtras.hasFileDescriptors()) { 17115 throw new IllegalArgumentException("File descriptors passed in Bundle"); 17116 } 17117 17118 final long origId = Binder.clearCallingIdentity(); 17119 try { 17120 boolean doNext = false; 17121 BroadcastRecord r; 17122 17123 synchronized(this) { 17124 BroadcastQueue queue = (flags & Intent.FLAG_RECEIVER_FOREGROUND) != 0 17125 ? mFgBroadcastQueue : mBgBroadcastQueue; 17126 r = queue.getMatchingOrderedReceiver(who); 17127 if (r != null) { 17128 doNext = r.queue.finishReceiverLocked(r, resultCode, 17129 resultData, resultExtras, resultAbort, true); 17130 } 17131 } 17132 17133 if (doNext) { 17134 r.queue.processNextBroadcast(false); 17135 } 17136 trimApplications(); 17137 } finally { 17138 Binder.restoreCallingIdentity(origId); 17139 } 17140 } 17141 17142 // ========================================================= 17143 // INSTRUMENTATION 17144 // ========================================================= 17145 startInstrumentation(ComponentName className, String profileFile, int flags, Bundle arguments, IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, int userId, String abiOverride)17146 public boolean startInstrumentation(ComponentName className, 17147 String profileFile, int flags, Bundle arguments, 17148 IInstrumentationWatcher watcher, IUiAutomationConnection uiAutomationConnection, 17149 int userId, String abiOverride) { 17150 enforceNotIsolatedCaller("startInstrumentation"); 17151 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 17152 userId, false, ALLOW_FULL_ONLY, "startInstrumentation", null); 17153 // Refuse possible leaked file descriptors 17154 if (arguments != null && arguments.hasFileDescriptors()) { 17155 throw new IllegalArgumentException("File descriptors passed in Bundle"); 17156 } 17157 17158 synchronized(this) { 17159 InstrumentationInfo ii = null; 17160 ApplicationInfo ai = null; 17161 try { 17162 ii = mContext.getPackageManager().getInstrumentationInfo( 17163 className, STOCK_PM_FLAGS); 17164 ai = AppGlobals.getPackageManager().getApplicationInfo( 17165 ii.targetPackage, STOCK_PM_FLAGS, userId); 17166 } catch (PackageManager.NameNotFoundException e) { 17167 } catch (RemoteException e) { 17168 } 17169 if (ii == null) { 17170 reportStartInstrumentationFailure(watcher, className, 17171 "Unable to find instrumentation info for: " + className); 17172 return false; 17173 } 17174 if (ai == null) { 17175 reportStartInstrumentationFailure(watcher, className, 17176 "Unable to find instrumentation target package: " + ii.targetPackage); 17177 return false; 17178 } 17179 17180 int match = mContext.getPackageManager().checkSignatures( 17181 ii.targetPackage, ii.packageName); 17182 if (match < 0 && match != PackageManager.SIGNATURE_FIRST_NOT_SIGNED) { 17183 String msg = "Permission Denial: starting instrumentation " 17184 + className + " from pid=" 17185 + Binder.getCallingPid() 17186 + ", uid=" + Binder.getCallingPid() 17187 + " not allowed because package " + ii.packageName 17188 + " does not have a signature matching the target " 17189 + ii.targetPackage; 17190 reportStartInstrumentationFailure(watcher, className, msg); 17191 throw new SecurityException(msg); 17192 } 17193 17194 final long origId = Binder.clearCallingIdentity(); 17195 // Instrumentation can kill and relaunch even persistent processes 17196 forceStopPackageLocked(ii.targetPackage, -1, true, false, true, true, false, userId, 17197 "start instr"); 17198 ProcessRecord app = addAppLocked(ai, false, abiOverride); 17199 app.instrumentationClass = className; 17200 app.instrumentationInfo = ai; 17201 app.instrumentationProfileFile = profileFile; 17202 app.instrumentationArguments = arguments; 17203 app.instrumentationWatcher = watcher; 17204 app.instrumentationUiAutomationConnection = uiAutomationConnection; 17205 app.instrumentationResultClass = className; 17206 Binder.restoreCallingIdentity(origId); 17207 } 17208 17209 return true; 17210 } 17211 17212 /** 17213 * Report errors that occur while attempting to start Instrumentation. Always writes the 17214 * error to the logs, but if somebody is watching, send the report there too. This enables 17215 * the "am" command to report errors with more information. 17216 * 17217 * @param watcher The IInstrumentationWatcher. Null if there isn't one. 17218 * @param cn The component name of the instrumentation. 17219 * @param report The error report. 17220 */ reportStartInstrumentationFailure(IInstrumentationWatcher watcher, ComponentName cn, String report)17221 private void reportStartInstrumentationFailure(IInstrumentationWatcher watcher, 17222 ComponentName cn, String report) { 17223 Slog.w(TAG, report); 17224 try { 17225 if (watcher != null) { 17226 Bundle results = new Bundle(); 17227 results.putString(Instrumentation.REPORT_KEY_IDENTIFIER, "ActivityManagerService"); 17228 results.putString("Error", report); 17229 watcher.instrumentationStatus(cn, -1, results); 17230 } 17231 } catch (RemoteException e) { 17232 Slog.w(TAG, e); 17233 } 17234 } 17235 finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results)17236 void finishInstrumentationLocked(ProcessRecord app, int resultCode, Bundle results) { 17237 if (app.instrumentationWatcher != null) { 17238 try { 17239 // NOTE: IInstrumentationWatcher *must* be oneway here 17240 app.instrumentationWatcher.instrumentationFinished( 17241 app.instrumentationClass, 17242 resultCode, 17243 results); 17244 } catch (RemoteException e) { 17245 } 17246 } 17247 17248 // Can't call out of the system process with a lock held, so post a message. 17249 if (app.instrumentationUiAutomationConnection != null) { 17250 mHandler.obtainMessage(SHUTDOWN_UI_AUTOMATION_CONNECTION_MSG, 17251 app.instrumentationUiAutomationConnection).sendToTarget(); 17252 } 17253 17254 app.instrumentationWatcher = null; 17255 app.instrumentationUiAutomationConnection = null; 17256 app.instrumentationClass = null; 17257 app.instrumentationInfo = null; 17258 app.instrumentationProfileFile = null; 17259 app.instrumentationArguments = null; 17260 17261 forceStopPackageLocked(app.info.packageName, -1, false, false, true, true, false, app.userId, 17262 "finished inst"); 17263 } 17264 finishInstrumentation(IApplicationThread target, int resultCode, Bundle results)17265 public void finishInstrumentation(IApplicationThread target, 17266 int resultCode, Bundle results) { 17267 int userId = UserHandle.getCallingUserId(); 17268 // Refuse possible leaked file descriptors 17269 if (results != null && results.hasFileDescriptors()) { 17270 throw new IllegalArgumentException("File descriptors passed in Intent"); 17271 } 17272 17273 synchronized(this) { 17274 ProcessRecord app = getRecordForAppLocked(target); 17275 if (app == null) { 17276 Slog.w(TAG, "finishInstrumentation: no app for " + target); 17277 return; 17278 } 17279 final long origId = Binder.clearCallingIdentity(); 17280 finishInstrumentationLocked(app, resultCode, results); 17281 Binder.restoreCallingIdentity(origId); 17282 } 17283 } 17284 17285 // ========================================================= 17286 // CONFIGURATION 17287 // ========================================================= 17288 getDeviceConfigurationInfo()17289 public ConfigurationInfo getDeviceConfigurationInfo() { 17290 ConfigurationInfo config = new ConfigurationInfo(); 17291 synchronized (this) { 17292 config.reqTouchScreen = mConfiguration.touchscreen; 17293 config.reqKeyboardType = mConfiguration.keyboard; 17294 config.reqNavigation = mConfiguration.navigation; 17295 if (mConfiguration.navigation == Configuration.NAVIGATION_DPAD 17296 || mConfiguration.navigation == Configuration.NAVIGATION_TRACKBALL) { 17297 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_FIVE_WAY_NAV; 17298 } 17299 if (mConfiguration.keyboard != Configuration.KEYBOARD_UNDEFINED 17300 && mConfiguration.keyboard != Configuration.KEYBOARD_NOKEYS) { 17301 config.reqInputFeatures |= ConfigurationInfo.INPUT_FEATURE_HARD_KEYBOARD; 17302 } 17303 config.reqGlEsVersion = GL_ES_VERSION; 17304 } 17305 return config; 17306 } 17307 getFocusedStack()17308 ActivityStack getFocusedStack() { 17309 return mStackSupervisor.getFocusedStack(); 17310 } 17311 17312 @Override getFocusedStackId()17313 public int getFocusedStackId() throws RemoteException { 17314 ActivityStack focusedStack = getFocusedStack(); 17315 if (focusedStack != null) { 17316 return focusedStack.getStackId(); 17317 } 17318 return -1; 17319 } 17320 getConfiguration()17321 public Configuration getConfiguration() { 17322 Configuration ci; 17323 synchronized(this) { 17324 ci = new Configuration(mConfiguration); 17325 ci.userSetLocale = false; 17326 } 17327 return ci; 17328 } 17329 updatePersistentConfiguration(Configuration values)17330 public void updatePersistentConfiguration(Configuration values) { 17331 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 17332 "updateConfiguration()"); 17333 enforceWriteSettingsPermission("updateConfiguration()"); 17334 if (values == null) { 17335 throw new NullPointerException("Configuration must not be null"); 17336 } 17337 17338 synchronized(this) { 17339 final long origId = Binder.clearCallingIdentity(); 17340 updateConfigurationLocked(values, null, true, false); 17341 Binder.restoreCallingIdentity(origId); 17342 } 17343 } 17344 enforceWriteSettingsPermission(String func)17345 private void enforceWriteSettingsPermission(String func) { 17346 int uid = Binder.getCallingUid(); 17347 if (uid == Process.ROOT_UID) { 17348 return; 17349 } 17350 17351 if (Settings.checkAndNoteWriteSettingsOperation(mContext, uid, 17352 Settings.getPackageNameForUid(mContext, uid), false)) { 17353 return; 17354 } 17355 17356 String msg = "Permission Denial: " + func + " from pid=" 17357 + Binder.getCallingPid() 17358 + ", uid=" + uid 17359 + " requires " + android.Manifest.permission.WRITE_SETTINGS; 17360 Slog.w(TAG, msg); 17361 throw new SecurityException(msg); 17362 } 17363 updateConfiguration(Configuration values)17364 public void updateConfiguration(Configuration values) { 17365 enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION, 17366 "updateConfiguration()"); 17367 17368 synchronized(this) { 17369 if (values == null && mWindowManager != null) { 17370 // sentinel: fetch the current configuration from the window manager 17371 values = mWindowManager.computeNewConfiguration(); 17372 } 17373 17374 if (mWindowManager != null) { 17375 mProcessList.applyDisplaySize(mWindowManager); 17376 } 17377 17378 final long origId = Binder.clearCallingIdentity(); 17379 if (values != null) { 17380 Settings.System.clearConfiguration(values); 17381 } 17382 updateConfigurationLocked(values, null, false, false); 17383 Binder.restoreCallingIdentity(origId); 17384 } 17385 } 17386 17387 /** 17388 * Do either or both things: (1) change the current configuration, and (2) 17389 * make sure the given activity is running with the (now) current 17390 * configuration. Returns true if the activity has been left running, or 17391 * false if <var>starting</var> is being destroyed to match the new 17392 * configuration. 17393 * @param persistent TODO 17394 */ updateConfigurationLocked(Configuration values, ActivityRecord starting, boolean persistent, boolean initLocale)17395 boolean updateConfigurationLocked(Configuration values, 17396 ActivityRecord starting, boolean persistent, boolean initLocale) { 17397 int changes = 0; 17398 17399 if (values != null) { 17400 Configuration newConfig = new Configuration(mConfiguration); 17401 changes = newConfig.updateFrom(values); 17402 if (changes != 0) { 17403 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.i(TAG_CONFIGURATION, 17404 "Updating configuration to: " + values); 17405 17406 EventLog.writeEvent(EventLogTags.CONFIGURATION_CHANGED, changes); 17407 17408 if (!initLocale && values.locale != null && values.userSetLocale) { 17409 final String languageTag = values.locale.toLanguageTag(); 17410 SystemProperties.set("persist.sys.locale", languageTag); 17411 mHandler.sendMessage(mHandler.obtainMessage(SEND_LOCALE_TO_MOUNT_DAEMON_MSG, 17412 values.locale)); 17413 } 17414 17415 mConfigurationSeq++; 17416 if (mConfigurationSeq <= 0) { 17417 mConfigurationSeq = 1; 17418 } 17419 newConfig.seq = mConfigurationSeq; 17420 mConfiguration = newConfig; 17421 Slog.i(TAG, "Config changes=" + Integer.toHexString(changes) + " " + newConfig); 17422 mUsageStatsService.reportConfigurationChange(newConfig, mCurrentUserId); 17423 //mUsageStatsService.noteStartConfig(newConfig); 17424 17425 final Configuration configCopy = new Configuration(mConfiguration); 17426 17427 // TODO: If our config changes, should we auto dismiss any currently 17428 // showing dialogs? 17429 mShowDialogs = shouldShowDialogs(newConfig); 17430 17431 AttributeCache ac = AttributeCache.instance(); 17432 if (ac != null) { 17433 ac.updateConfiguration(configCopy); 17434 } 17435 17436 // Make sure all resources in our process are updated 17437 // right now, so that anyone who is going to retrieve 17438 // resource values after we return will be sure to get 17439 // the new ones. This is especially important during 17440 // boot, where the first config change needs to guarantee 17441 // all resources have that config before following boot 17442 // code is executed. 17443 mSystemThread.applyConfigurationToResources(configCopy); 17444 17445 if (persistent && Settings.System.hasInterestingConfigurationChanges(changes)) { 17446 Message msg = mHandler.obtainMessage(UPDATE_CONFIGURATION_MSG); 17447 msg.obj = new Configuration(configCopy); 17448 mHandler.sendMessage(msg); 17449 } 17450 17451 for (int i=mLruProcesses.size()-1; i>=0; i--) { 17452 ProcessRecord app = mLruProcesses.get(i); 17453 try { 17454 if (app.thread != null) { 17455 if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, "Sending to proc " 17456 + app.processName + " new config " + mConfiguration); 17457 app.thread.scheduleConfigurationChanged(configCopy); 17458 } 17459 } catch (Exception e) { 17460 } 17461 } 17462 Intent intent = new Intent(Intent.ACTION_CONFIGURATION_CHANGED); 17463 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 17464 | Intent.FLAG_RECEIVER_REPLACE_PENDING 17465 | Intent.FLAG_RECEIVER_FOREGROUND); 17466 broadcastIntentLocked(null, null, intent, null, null, 0, null, null, 17467 null, AppOpsManager.OP_NONE, null, false, false, 17468 MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 17469 if ((changes&ActivityInfo.CONFIG_LOCALE) != 0) { 17470 intent = new Intent(Intent.ACTION_LOCALE_CHANGED); 17471 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 17472 if (!mProcessesReady) { 17473 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 17474 } 17475 broadcastIntentLocked(null, null, intent, 17476 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 17477 null, false, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 17478 } 17479 } 17480 } 17481 17482 boolean kept = true; 17483 final ActivityStack mainStack = mStackSupervisor.getFocusedStack(); 17484 // mainStack is null during startup. 17485 if (mainStack != null) { 17486 if (changes != 0 && starting == null) { 17487 // If the configuration changed, and the caller is not already 17488 // in the process of starting an activity, then find the top 17489 // activity to check if its configuration needs to change. 17490 starting = mainStack.topRunningActivityLocked(null); 17491 } 17492 17493 if (starting != null) { 17494 kept = mainStack.ensureActivityConfigurationLocked(starting, changes); 17495 // And we need to make sure at this point that all other activities 17496 // are made visible with the correct configuration. 17497 mStackSupervisor.ensureActivitiesVisibleLocked(starting, changes); 17498 } 17499 } 17500 17501 if (values != null && mWindowManager != null) { 17502 mWindowManager.setNewConfiguration(mConfiguration); 17503 } 17504 17505 return kept; 17506 } 17507 17508 /** 17509 * Decide based on the configuration whether we should shouw the ANR, 17510 * crash, etc dialogs. The idea is that if there is no affordnace to 17511 * press the on-screen buttons, we shouldn't show the dialog. 17512 * 17513 * A thought: SystemUI might also want to get told about this, the Power 17514 * dialog / global actions also might want different behaviors. 17515 */ shouldShowDialogs(Configuration config)17516 private static final boolean shouldShowDialogs(Configuration config) { 17517 return !(config.keyboard == Configuration.KEYBOARD_NOKEYS 17518 && config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH 17519 && config.navigation == Configuration.NAVIGATION_NONAV); 17520 } 17521 17522 @Override shouldUpRecreateTask(IBinder token, String destAffinity)17523 public boolean shouldUpRecreateTask(IBinder token, String destAffinity) { 17524 synchronized (this) { 17525 ActivityRecord srec = ActivityRecord.forTokenLocked(token); 17526 if (srec != null) { 17527 return srec.task.stack.shouldUpRecreateTaskLocked(srec, destAffinity); 17528 } 17529 } 17530 return false; 17531 } 17532 navigateUpTo(IBinder token, Intent destIntent, int resultCode, Intent resultData)17533 public boolean navigateUpTo(IBinder token, Intent destIntent, int resultCode, 17534 Intent resultData) { 17535 17536 synchronized (this) { 17537 final ActivityRecord r = ActivityRecord.forTokenLocked(token); 17538 if (r != null) { 17539 return r.task.stack.navigateUpToLocked(r, destIntent, resultCode, resultData); 17540 } 17541 return false; 17542 } 17543 } 17544 getLaunchedFromUid(IBinder activityToken)17545 public int getLaunchedFromUid(IBinder activityToken) { 17546 ActivityRecord srec; 17547 synchronized (this) { 17548 srec = ActivityRecord.forTokenLocked(activityToken); 17549 } 17550 if (srec == null) { 17551 return -1; 17552 } 17553 return srec.launchedFromUid; 17554 } 17555 getLaunchedFromPackage(IBinder activityToken)17556 public String getLaunchedFromPackage(IBinder activityToken) { 17557 ActivityRecord srec; 17558 synchronized (this) { 17559 srec = ActivityRecord.forTokenLocked(activityToken); 17560 } 17561 if (srec == null) { 17562 return null; 17563 } 17564 return srec.launchedFromPackage; 17565 } 17566 17567 // ========================================================= 17568 // LIFETIME MANAGEMENT 17569 // ========================================================= 17570 17571 // Returns which broadcast queue the app is the current [or imminent] receiver 17572 // on, or 'null' if the app is not an active broadcast recipient. isReceivingBroadcast(ProcessRecord app)17573 private BroadcastQueue isReceivingBroadcast(ProcessRecord app) { 17574 BroadcastRecord r = app.curReceiver; 17575 if (r != null) { 17576 return r.queue; 17577 } 17578 17579 // It's not the current receiver, but it might be starting up to become one 17580 synchronized (this) { 17581 for (BroadcastQueue queue : mBroadcastQueues) { 17582 r = queue.mPendingBroadcast; 17583 if (r != null && r.curApp == app) { 17584 // found it; report which queue it's in 17585 return queue; 17586 } 17587 } 17588 } 17589 17590 return null; 17591 } 17592 startAssociationLocked(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent, String targetProcess)17593 Association startAssociationLocked(int sourceUid, String sourceProcess, int targetUid, 17594 ComponentName targetComponent, String targetProcess) { 17595 if (!mTrackingAssociations) { 17596 return null; 17597 } 17598 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 17599 = mAssociations.get(targetUid); 17600 if (components == null) { 17601 components = new ArrayMap<>(); 17602 mAssociations.put(targetUid, components); 17603 } 17604 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 17605 if (sourceUids == null) { 17606 sourceUids = new SparseArray<>(); 17607 components.put(targetComponent, sourceUids); 17608 } 17609 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 17610 if (sourceProcesses == null) { 17611 sourceProcesses = new ArrayMap<>(); 17612 sourceUids.put(sourceUid, sourceProcesses); 17613 } 17614 Association ass = sourceProcesses.get(sourceProcess); 17615 if (ass == null) { 17616 ass = new Association(sourceUid, sourceProcess, targetUid, targetComponent, 17617 targetProcess); 17618 sourceProcesses.put(sourceProcess, ass); 17619 } 17620 ass.mCount++; 17621 ass.mNesting++; 17622 if (ass.mNesting == 1) { 17623 ass.mStartTime = SystemClock.uptimeMillis(); 17624 } 17625 return ass; 17626 } 17627 stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, ComponentName targetComponent)17628 void stopAssociationLocked(int sourceUid, String sourceProcess, int targetUid, 17629 ComponentName targetComponent) { 17630 if (!mTrackingAssociations) { 17631 return; 17632 } 17633 ArrayMap<ComponentName, SparseArray<ArrayMap<String, Association>>> components 17634 = mAssociations.get(targetUid); 17635 if (components == null) { 17636 return; 17637 } 17638 SparseArray<ArrayMap<String, Association>> sourceUids = components.get(targetComponent); 17639 if (sourceUids == null) { 17640 return; 17641 } 17642 ArrayMap<String, Association> sourceProcesses = sourceUids.get(sourceUid); 17643 if (sourceProcesses == null) { 17644 return; 17645 } 17646 Association ass = sourceProcesses.get(sourceProcess); 17647 if (ass == null || ass.mNesting <= 0) { 17648 return; 17649 } 17650 ass.mNesting--; 17651 if (ass.mNesting == 0) { 17652 ass.mTime += SystemClock.uptimeMillis() - ass.mStartTime; 17653 } 17654 } 17655 computeOomAdjLocked(ProcessRecord app, int cachedAdj, ProcessRecord TOP_APP, boolean doingAll, long now)17656 private final int computeOomAdjLocked(ProcessRecord app, int cachedAdj, ProcessRecord TOP_APP, 17657 boolean doingAll, long now) { 17658 if (mAdjSeq == app.adjSeq) { 17659 // This adjustment has already been computed. 17660 return app.curRawAdj; 17661 } 17662 17663 if (app.thread == null) { 17664 app.adjSeq = mAdjSeq; 17665 app.curSchedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 17666 app.curProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 17667 return (app.curAdj=app.curRawAdj=ProcessList.CACHED_APP_MAX_ADJ); 17668 } 17669 17670 app.adjTypeCode = ActivityManager.RunningAppProcessInfo.REASON_UNKNOWN; 17671 app.adjSource = null; 17672 app.adjTarget = null; 17673 app.empty = false; 17674 app.cached = false; 17675 17676 final int activitiesSize = app.activities.size(); 17677 17678 if (app.maxAdj <= ProcessList.FOREGROUND_APP_ADJ) { 17679 // The max adjustment doesn't allow this app to be anything 17680 // below foreground, so it is not worth doing work for it. 17681 app.adjType = "fixed"; 17682 app.adjSeq = mAdjSeq; 17683 app.curRawAdj = app.maxAdj; 17684 app.foregroundActivities = false; 17685 app.curSchedGroup = Process.THREAD_GROUP_DEFAULT; 17686 app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT; 17687 // System processes can do UI, and when they do we want to have 17688 // them trim their memory after the user leaves the UI. To 17689 // facilitate this, here we need to determine whether or not it 17690 // is currently showing UI. 17691 app.systemNoUi = true; 17692 if (app == TOP_APP) { 17693 app.systemNoUi = false; 17694 } else if (activitiesSize > 0) { 17695 for (int j = 0; j < activitiesSize; j++) { 17696 final ActivityRecord r = app.activities.get(j); 17697 if (r.visible) { 17698 app.systemNoUi = false; 17699 } 17700 } 17701 } 17702 if (!app.systemNoUi) { 17703 app.curProcState = ActivityManager.PROCESS_STATE_PERSISTENT_UI; 17704 } 17705 return (app.curAdj=app.maxAdj); 17706 } 17707 17708 app.systemNoUi = false; 17709 17710 final int PROCESS_STATE_TOP = mTopProcessState; 17711 17712 // Determine the importance of the process, starting with most 17713 // important to least, and assign an appropriate OOM adjustment. 17714 int adj; 17715 int schedGroup; 17716 int procState; 17717 boolean foregroundActivities = false; 17718 BroadcastQueue queue; 17719 if (app == TOP_APP) { 17720 // The last app on the list is the foreground app. 17721 adj = ProcessList.FOREGROUND_APP_ADJ; 17722 schedGroup = Process.THREAD_GROUP_DEFAULT; 17723 app.adjType = "top-activity"; 17724 foregroundActivities = true; 17725 procState = PROCESS_STATE_TOP; 17726 } else if (app.instrumentationClass != null) { 17727 // Don't want to kill running instrumentation. 17728 adj = ProcessList.FOREGROUND_APP_ADJ; 17729 schedGroup = Process.THREAD_GROUP_DEFAULT; 17730 app.adjType = "instrumentation"; 17731 procState = ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE; 17732 } else if ((queue = isReceivingBroadcast(app)) != null) { 17733 // An app that is currently receiving a broadcast also 17734 // counts as being in the foreground for OOM killer purposes. 17735 // It's placed in a sched group based on the nature of the 17736 // broadcast as reflected by which queue it's active in. 17737 adj = ProcessList.FOREGROUND_APP_ADJ; 17738 schedGroup = (queue == mFgBroadcastQueue) 17739 ? Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE; 17740 app.adjType = "broadcast"; 17741 procState = ActivityManager.PROCESS_STATE_RECEIVER; 17742 } else if (app.executingServices.size() > 0) { 17743 // An app that is currently executing a service callback also 17744 // counts as being in the foreground. 17745 adj = ProcessList.FOREGROUND_APP_ADJ; 17746 schedGroup = app.execServicesFg ? 17747 Process.THREAD_GROUP_DEFAULT : Process.THREAD_GROUP_BG_NONINTERACTIVE; 17748 app.adjType = "exec-service"; 17749 procState = ActivityManager.PROCESS_STATE_SERVICE; 17750 //Slog.i(TAG, "EXEC " + (app.execServicesFg ? "FG" : "BG") + ": " + app); 17751 } else { 17752 // As far as we know the process is empty. We may change our mind later. 17753 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 17754 // At this point we don't actually know the adjustment. Use the cached adj 17755 // value that the caller wants us to. 17756 adj = cachedAdj; 17757 procState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 17758 app.cached = true; 17759 app.empty = true; 17760 app.adjType = "cch-empty"; 17761 } 17762 17763 // Examine all activities if not already foreground. 17764 if (!foregroundActivities && activitiesSize > 0) { 17765 for (int j = 0; j < activitiesSize; j++) { 17766 final ActivityRecord r = app.activities.get(j); 17767 if (r.app != app) { 17768 Slog.w(TAG, "Wtf, activity " + r + " in proc activity list not using proc " 17769 + app + "?!? Using " + r.app + " instead."); 17770 continue; 17771 } 17772 if (r.visible) { 17773 // App has a visible activity; only upgrade adjustment. 17774 if (adj > ProcessList.VISIBLE_APP_ADJ) { 17775 adj = ProcessList.VISIBLE_APP_ADJ; 17776 app.adjType = "visible"; 17777 } 17778 if (procState > PROCESS_STATE_TOP) { 17779 procState = PROCESS_STATE_TOP; 17780 } 17781 schedGroup = Process.THREAD_GROUP_DEFAULT; 17782 app.cached = false; 17783 app.empty = false; 17784 foregroundActivities = true; 17785 break; 17786 } else if (r.state == ActivityState.PAUSING || r.state == ActivityState.PAUSED) { 17787 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 17788 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 17789 app.adjType = "pausing"; 17790 } 17791 if (procState > PROCESS_STATE_TOP) { 17792 procState = PROCESS_STATE_TOP; 17793 } 17794 schedGroup = Process.THREAD_GROUP_DEFAULT; 17795 app.cached = false; 17796 app.empty = false; 17797 foregroundActivities = true; 17798 } else if (r.state == ActivityState.STOPPING) { 17799 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 17800 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 17801 app.adjType = "stopping"; 17802 } 17803 // For the process state, we will at this point consider the 17804 // process to be cached. It will be cached either as an activity 17805 // or empty depending on whether the activity is finishing. We do 17806 // this so that we can treat the process as cached for purposes of 17807 // memory trimming (determing current memory level, trim command to 17808 // send to process) since there can be an arbitrary number of stopping 17809 // processes and they should soon all go into the cached state. 17810 if (!r.finishing) { 17811 if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 17812 procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY; 17813 } 17814 } 17815 app.cached = false; 17816 app.empty = false; 17817 foregroundActivities = true; 17818 } else { 17819 if (procState > ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 17820 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 17821 app.adjType = "cch-act"; 17822 } 17823 } 17824 } 17825 } 17826 17827 if (adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 17828 if (app.foregroundServices) { 17829 // The user is aware of this app, so make it visible. 17830 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 17831 procState = ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE; 17832 app.cached = false; 17833 app.adjType = "fg-service"; 17834 schedGroup = Process.THREAD_GROUP_DEFAULT; 17835 } else if (app.forcingToForeground != null) { 17836 // The user is aware of this app, so make it visible. 17837 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 17838 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 17839 app.cached = false; 17840 app.adjType = "force-fg"; 17841 app.adjSource = app.forcingToForeground; 17842 schedGroup = Process.THREAD_GROUP_DEFAULT; 17843 } 17844 } 17845 17846 if (app == mHeavyWeightProcess) { 17847 if (adj > ProcessList.HEAVY_WEIGHT_APP_ADJ) { 17848 // We don't want to kill the current heavy-weight process. 17849 adj = ProcessList.HEAVY_WEIGHT_APP_ADJ; 17850 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 17851 app.cached = false; 17852 app.adjType = "heavy"; 17853 } 17854 if (procState > ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 17855 procState = ActivityManager.PROCESS_STATE_HEAVY_WEIGHT; 17856 } 17857 } 17858 17859 if (app == mHomeProcess) { 17860 if (adj > ProcessList.HOME_APP_ADJ) { 17861 // This process is hosting what we currently consider to be the 17862 // home app, so we don't want to let it go into the background. 17863 adj = ProcessList.HOME_APP_ADJ; 17864 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 17865 app.cached = false; 17866 app.adjType = "home"; 17867 } 17868 if (procState > ActivityManager.PROCESS_STATE_HOME) { 17869 procState = ActivityManager.PROCESS_STATE_HOME; 17870 } 17871 } 17872 17873 if (app == mPreviousProcess && app.activities.size() > 0) { 17874 if (adj > ProcessList.PREVIOUS_APP_ADJ) { 17875 // This was the previous process that showed UI to the user. 17876 // We want to try to keep it around more aggressively, to give 17877 // a good experience around switching between two apps. 17878 adj = ProcessList.PREVIOUS_APP_ADJ; 17879 schedGroup = Process.THREAD_GROUP_BG_NONINTERACTIVE; 17880 app.cached = false; 17881 app.adjType = "previous"; 17882 } 17883 if (procState > ActivityManager.PROCESS_STATE_LAST_ACTIVITY) { 17884 procState = ActivityManager.PROCESS_STATE_LAST_ACTIVITY; 17885 } 17886 } 17887 17888 if (false) Slog.i(TAG, "OOM " + app + ": initial adj=" + adj 17889 + " reason=" + app.adjType); 17890 17891 // By default, we use the computed adjustment. It may be changed if 17892 // there are applications dependent on our services or providers, but 17893 // this gives us a baseline and makes sure we don't get into an 17894 // infinite recursion. 17895 app.adjSeq = mAdjSeq; 17896 app.curRawAdj = adj; 17897 app.hasStartedServices = false; 17898 17899 if (mBackupTarget != null && app == mBackupTarget.app) { 17900 // If possible we want to avoid killing apps while they're being backed up 17901 if (adj > ProcessList.BACKUP_APP_ADJ) { 17902 if (DEBUG_BACKUP) Slog.v(TAG_BACKUP, "oom BACKUP_APP_ADJ for " + app); 17903 adj = ProcessList.BACKUP_APP_ADJ; 17904 if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) { 17905 procState = ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND; 17906 } 17907 app.adjType = "backup"; 17908 app.cached = false; 17909 } 17910 if (procState > ActivityManager.PROCESS_STATE_BACKUP) { 17911 procState = ActivityManager.PROCESS_STATE_BACKUP; 17912 } 17913 } 17914 17915 boolean mayBeTop = false; 17916 17917 for (int is = app.services.size()-1; 17918 is >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 17919 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 17920 || procState > ActivityManager.PROCESS_STATE_TOP); 17921 is--) { 17922 ServiceRecord s = app.services.valueAt(is); 17923 if (s.startRequested) { 17924 app.hasStartedServices = true; 17925 if (procState > ActivityManager.PROCESS_STATE_SERVICE) { 17926 procState = ActivityManager.PROCESS_STATE_SERVICE; 17927 } 17928 if (app.hasShownUi && app != mHomeProcess) { 17929 // If this process has shown some UI, let it immediately 17930 // go to the LRU list because it may be pretty heavy with 17931 // UI stuff. We'll tag it with a label just to help 17932 // debug and understand what is going on. 17933 if (adj > ProcessList.SERVICE_ADJ) { 17934 app.adjType = "cch-started-ui-services"; 17935 } 17936 } else { 17937 if (now < (s.lastActivity + ActiveServices.MAX_SERVICE_INACTIVITY)) { 17938 // This service has seen some activity within 17939 // recent memory, so we will keep its process ahead 17940 // of the background processes. 17941 if (adj > ProcessList.SERVICE_ADJ) { 17942 adj = ProcessList.SERVICE_ADJ; 17943 app.adjType = "started-services"; 17944 app.cached = false; 17945 } 17946 } 17947 // If we have let the service slide into the background 17948 // state, still have some text describing what it is doing 17949 // even though the service no longer has an impact. 17950 if (adj > ProcessList.SERVICE_ADJ) { 17951 app.adjType = "cch-started-services"; 17952 } 17953 } 17954 } 17955 for (int conni = s.connections.size()-1; 17956 conni >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 17957 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 17958 || procState > ActivityManager.PROCESS_STATE_TOP); 17959 conni--) { 17960 ArrayList<ConnectionRecord> clist = s.connections.valueAt(conni); 17961 for (int i = 0; 17962 i < clist.size() && (adj > ProcessList.FOREGROUND_APP_ADJ 17963 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 17964 || procState > ActivityManager.PROCESS_STATE_TOP); 17965 i++) { 17966 // XXX should compute this based on the max of 17967 // all connected clients. 17968 ConnectionRecord cr = clist.get(i); 17969 if (cr.binding.client == app) { 17970 // Binding to ourself is not interesting. 17971 continue; 17972 } 17973 if ((cr.flags&Context.BIND_WAIVE_PRIORITY) == 0) { 17974 ProcessRecord client = cr.binding.client; 17975 int clientAdj = computeOomAdjLocked(client, cachedAdj, 17976 TOP_APP, doingAll, now); 17977 int clientProcState = client.curProcState; 17978 if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 17979 // If the other app is cached for any reason, for purposes here 17980 // we are going to consider it empty. The specific cached state 17981 // doesn't propagate except under certain conditions. 17982 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 17983 } 17984 String adjType = null; 17985 if ((cr.flags&Context.BIND_ALLOW_OOM_MANAGEMENT) != 0) { 17986 // Not doing bind OOM management, so treat 17987 // this guy more like a started service. 17988 if (app.hasShownUi && app != mHomeProcess) { 17989 // If this process has shown some UI, let it immediately 17990 // go to the LRU list because it may be pretty heavy with 17991 // UI stuff. We'll tag it with a label just to help 17992 // debug and understand what is going on. 17993 if (adj > clientAdj) { 17994 adjType = "cch-bound-ui-services"; 17995 } 17996 app.cached = false; 17997 clientAdj = adj; 17998 clientProcState = procState; 17999 } else { 18000 if (now >= (s.lastActivity 18001 + ActiveServices.MAX_SERVICE_INACTIVITY)) { 18002 // This service has not seen activity within 18003 // recent memory, so allow it to drop to the 18004 // LRU list if there is no other reason to keep 18005 // it around. We'll also tag it with a label just 18006 // to help debug and undertand what is going on. 18007 if (adj > clientAdj) { 18008 adjType = "cch-bound-services"; 18009 } 18010 clientAdj = adj; 18011 } 18012 } 18013 } 18014 if (adj > clientAdj) { 18015 // If this process has recently shown UI, and 18016 // the process that is binding to it is less 18017 // important than being visible, then we don't 18018 // care about the binding as much as we care 18019 // about letting this process get into the LRU 18020 // list to be killed and restarted if needed for 18021 // memory. 18022 if (app.hasShownUi && app != mHomeProcess 18023 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 18024 adjType = "cch-bound-ui-services"; 18025 } else { 18026 if ((cr.flags&(Context.BIND_ABOVE_CLIENT 18027 |Context.BIND_IMPORTANT)) != 0) { 18028 adj = clientAdj >= ProcessList.PERSISTENT_SERVICE_ADJ 18029 ? clientAdj : ProcessList.PERSISTENT_SERVICE_ADJ; 18030 } else if ((cr.flags&Context.BIND_NOT_VISIBLE) != 0 18031 && clientAdj < ProcessList.PERCEPTIBLE_APP_ADJ 18032 && adj > ProcessList.PERCEPTIBLE_APP_ADJ) { 18033 adj = ProcessList.PERCEPTIBLE_APP_ADJ; 18034 } else if (clientAdj > ProcessList.VISIBLE_APP_ADJ) { 18035 adj = clientAdj; 18036 } else { 18037 if (adj > ProcessList.VISIBLE_APP_ADJ) { 18038 adj = ProcessList.VISIBLE_APP_ADJ; 18039 } 18040 } 18041 if (!client.cached) { 18042 app.cached = false; 18043 } 18044 adjType = "service"; 18045 } 18046 } 18047 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) { 18048 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) { 18049 schedGroup = Process.THREAD_GROUP_DEFAULT; 18050 } 18051 if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) { 18052 if (clientProcState == ActivityManager.PROCESS_STATE_TOP) { 18053 // Special handling of clients who are in the top state. 18054 // We *may* want to consider this process to be in the 18055 // top state as well, but only if there is not another 18056 // reason for it to be running. Being on the top is a 18057 // special state, meaning you are specifically running 18058 // for the current top app. If the process is already 18059 // running in the background for some other reason, it 18060 // is more important to continue considering it to be 18061 // in the background state. 18062 mayBeTop = true; 18063 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 18064 } else { 18065 // Special handling for above-top states (persistent 18066 // processes). These should not bring the current process 18067 // into the top state, since they are not on top. Instead 18068 // give them the best state after that. 18069 if ((cr.flags&Context.BIND_FOREGROUND_SERVICE) != 0) { 18070 clientProcState = 18071 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE; 18072 } else if (mWakefulness 18073 == PowerManagerInternal.WAKEFULNESS_AWAKE && 18074 (cr.flags&Context.BIND_FOREGROUND_SERVICE_WHILE_AWAKE) 18075 != 0) { 18076 clientProcState = 18077 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE; 18078 } else { 18079 clientProcState = 18080 ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 18081 } 18082 } 18083 } 18084 } else { 18085 if (clientProcState < 18086 ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND) { 18087 clientProcState = 18088 ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND; 18089 } 18090 } 18091 if (procState > clientProcState) { 18092 procState = clientProcState; 18093 } 18094 if (procState < ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 18095 && (cr.flags&Context.BIND_SHOWING_UI) != 0) { 18096 app.pendingUiClean = true; 18097 } 18098 if (adjType != null) { 18099 app.adjType = adjType; 18100 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 18101 .REASON_SERVICE_IN_USE; 18102 app.adjSource = cr.binding.client; 18103 app.adjSourceProcState = clientProcState; 18104 app.adjTarget = s.name; 18105 } 18106 } 18107 if ((cr.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) { 18108 app.treatLikeActivity = true; 18109 } 18110 final ActivityRecord a = cr.activity; 18111 if ((cr.flags&Context.BIND_ADJUST_WITH_ACTIVITY) != 0) { 18112 if (a != null && adj > ProcessList.FOREGROUND_APP_ADJ && 18113 (a.visible || a.state == ActivityState.RESUMED 18114 || a.state == ActivityState.PAUSING)) { 18115 adj = ProcessList.FOREGROUND_APP_ADJ; 18116 if ((cr.flags&Context.BIND_NOT_FOREGROUND) == 0) { 18117 schedGroup = Process.THREAD_GROUP_DEFAULT; 18118 } 18119 app.cached = false; 18120 app.adjType = "service"; 18121 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 18122 .REASON_SERVICE_IN_USE; 18123 app.adjSource = a; 18124 app.adjSourceProcState = procState; 18125 app.adjTarget = s.name; 18126 } 18127 } 18128 } 18129 } 18130 } 18131 18132 for (int provi = app.pubProviders.size()-1; 18133 provi >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 18134 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 18135 || procState > ActivityManager.PROCESS_STATE_TOP); 18136 provi--) { 18137 ContentProviderRecord cpr = app.pubProviders.valueAt(provi); 18138 for (int i = cpr.connections.size()-1; 18139 i >= 0 && (adj > ProcessList.FOREGROUND_APP_ADJ 18140 || schedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE 18141 || procState > ActivityManager.PROCESS_STATE_TOP); 18142 i--) { 18143 ContentProviderConnection conn = cpr.connections.get(i); 18144 ProcessRecord client = conn.client; 18145 if (client == app) { 18146 // Being our own client is not interesting. 18147 continue; 18148 } 18149 int clientAdj = computeOomAdjLocked(client, cachedAdj, TOP_APP, doingAll, now); 18150 int clientProcState = client.curProcState; 18151 if (clientProcState >= ActivityManager.PROCESS_STATE_CACHED_ACTIVITY) { 18152 // If the other app is cached for any reason, for purposes here 18153 // we are going to consider it empty. 18154 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 18155 } 18156 if (adj > clientAdj) { 18157 if (app.hasShownUi && app != mHomeProcess 18158 && clientAdj > ProcessList.PERCEPTIBLE_APP_ADJ) { 18159 app.adjType = "cch-ui-provider"; 18160 } else { 18161 adj = clientAdj > ProcessList.FOREGROUND_APP_ADJ 18162 ? clientAdj : ProcessList.FOREGROUND_APP_ADJ; 18163 app.adjType = "provider"; 18164 } 18165 app.cached &= client.cached; 18166 app.adjTypeCode = ActivityManager.RunningAppProcessInfo 18167 .REASON_PROVIDER_IN_USE; 18168 app.adjSource = client; 18169 app.adjSourceProcState = clientProcState; 18170 app.adjTarget = cpr.name; 18171 } 18172 if (clientProcState <= ActivityManager.PROCESS_STATE_TOP) { 18173 if (clientProcState == ActivityManager.PROCESS_STATE_TOP) { 18174 // Special handling of clients who are in the top state. 18175 // We *may* want to consider this process to be in the 18176 // top state as well, but only if there is not another 18177 // reason for it to be running. Being on the top is a 18178 // special state, meaning you are specifically running 18179 // for the current top app. If the process is already 18180 // running in the background for some other reason, it 18181 // is more important to continue considering it to be 18182 // in the background state. 18183 mayBeTop = true; 18184 clientProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY; 18185 } else { 18186 // Special handling for above-top states (persistent 18187 // processes). These should not bring the current process 18188 // into the top state, since they are not on top. Instead 18189 // give them the best state after that. 18190 clientProcState = 18191 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE; 18192 } 18193 } 18194 if (procState > clientProcState) { 18195 procState = clientProcState; 18196 } 18197 if (client.curSchedGroup == Process.THREAD_GROUP_DEFAULT) { 18198 schedGroup = Process.THREAD_GROUP_DEFAULT; 18199 } 18200 } 18201 // If the provider has external (non-framework) process 18202 // dependencies, ensure that its adjustment is at least 18203 // FOREGROUND_APP_ADJ. 18204 if (cpr.hasExternalProcessHandles()) { 18205 if (adj > ProcessList.FOREGROUND_APP_ADJ) { 18206 adj = ProcessList.FOREGROUND_APP_ADJ; 18207 schedGroup = Process.THREAD_GROUP_DEFAULT; 18208 app.cached = false; 18209 app.adjType = "provider"; 18210 app.adjTarget = cpr.name; 18211 } 18212 if (procState > ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { 18213 procState = ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 18214 } 18215 } 18216 } 18217 18218 if (mayBeTop && procState > ActivityManager.PROCESS_STATE_TOP) { 18219 // A client of one of our services or providers is in the top state. We 18220 // *may* want to be in the top state, but not if we are already running in 18221 // the background for some other reason. For the decision here, we are going 18222 // to pick out a few specific states that we want to remain in when a client 18223 // is top (states that tend to be longer-term) and otherwise allow it to go 18224 // to the top state. 18225 switch (procState) { 18226 case ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND: 18227 case ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND: 18228 case ActivityManager.PROCESS_STATE_SERVICE: 18229 // These all are longer-term states, so pull them up to the top 18230 // of the background states, but not all the way to the top state. 18231 procState = ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE; 18232 break; 18233 default: 18234 // Otherwise, top is a better choice, so take it. 18235 procState = ActivityManager.PROCESS_STATE_TOP; 18236 break; 18237 } 18238 } 18239 18240 if (procState >= ActivityManager.PROCESS_STATE_CACHED_EMPTY) { 18241 if (app.hasClientActivities) { 18242 // This is a cached process, but with client activities. Mark it so. 18243 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT; 18244 app.adjType = "cch-client-act"; 18245 } else if (app.treatLikeActivity) { 18246 // This is a cached process, but somebody wants us to treat it like it has 18247 // an activity, okay! 18248 procState = ActivityManager.PROCESS_STATE_CACHED_ACTIVITY; 18249 app.adjType = "cch-as-act"; 18250 } 18251 } 18252 18253 if (adj == ProcessList.SERVICE_ADJ) { 18254 if (doingAll) { 18255 app.serviceb = mNewNumAServiceProcs > (mNumServiceProcs/3); 18256 mNewNumServiceProcs++; 18257 //Slog.i(TAG, "ADJ " + app + " serviceb=" + app.serviceb); 18258 if (!app.serviceb) { 18259 // This service isn't far enough down on the LRU list to 18260 // normally be a B service, but if we are low on RAM and it 18261 // is large we want to force it down since we would prefer to 18262 // keep launcher over it. 18263 if (mLastMemoryLevel > ProcessStats.ADJ_MEM_FACTOR_NORMAL 18264 && app.lastPss >= mProcessList.getCachedRestoreThresholdKb()) { 18265 app.serviceHighRam = true; 18266 app.serviceb = true; 18267 //Slog.i(TAG, "ADJ " + app + " high ram!"); 18268 } else { 18269 mNewNumAServiceProcs++; 18270 //Slog.i(TAG, "ADJ " + app + " not high ram!"); 18271 } 18272 } else { 18273 app.serviceHighRam = false; 18274 } 18275 } 18276 if (app.serviceb) { 18277 adj = ProcessList.SERVICE_B_ADJ; 18278 } 18279 } 18280 18281 app.curRawAdj = adj; 18282 18283 //Slog.i(TAG, "OOM ADJ " + app + ": pid=" + app.pid + 18284 // " adj=" + adj + " curAdj=" + app.curAdj + " maxAdj=" + app.maxAdj); 18285 if (adj > app.maxAdj) { 18286 adj = app.maxAdj; 18287 if (app.maxAdj <= ProcessList.PERCEPTIBLE_APP_ADJ) { 18288 schedGroup = Process.THREAD_GROUP_DEFAULT; 18289 } 18290 } 18291 18292 // Do final modification to adj. Everything we do between here and applying 18293 // the final setAdj must be done in this function, because we will also use 18294 // it when computing the final cached adj later. Note that we don't need to 18295 // worry about this for max adj above, since max adj will always be used to 18296 // keep it out of the cached vaues. 18297 app.curAdj = app.modifyRawOomAdj(adj); 18298 app.curSchedGroup = schedGroup; 18299 app.curProcState = procState; 18300 app.foregroundActivities = foregroundActivities; 18301 18302 return app.curRawAdj; 18303 } 18304 18305 /** 18306 * Record new PSS sample for a process. 18307 */ recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long now)18308 void recordPssSampleLocked(ProcessRecord proc, int procState, long pss, long uss, long now) { 18309 EventLogTags.writeAmPss(proc.pid, proc.uid, proc.processName, pss * 1024, uss * 1024); 18310 proc.lastPssTime = now; 18311 proc.baseProcessTracker.addPss(pss, uss, true, proc.pkgList); 18312 if (DEBUG_PSS) Slog.d(TAG_PSS, 18313 "PSS of " + proc.toShortString() + ": " + pss + " lastPss=" + proc.lastPss 18314 + " state=" + ProcessList.makeProcStateString(procState)); 18315 if (proc.initialIdlePss == 0) { 18316 proc.initialIdlePss = pss; 18317 } 18318 proc.lastPss = pss; 18319 if (procState >= ActivityManager.PROCESS_STATE_HOME) { 18320 proc.lastCachedPss = pss; 18321 } 18322 18323 final SparseArray<Pair<Long, String>> watchUids 18324 = mMemWatchProcesses.getMap().get(proc.processName); 18325 Long check = null; 18326 if (watchUids != null) { 18327 Pair<Long, String> val = watchUids.get(proc.uid); 18328 if (val == null) { 18329 val = watchUids.get(0); 18330 } 18331 if (val != null) { 18332 check = val.first; 18333 } 18334 } 18335 if (check != null) { 18336 if ((pss * 1024) >= check && proc.thread != null && mMemWatchDumpProcName == null) { 18337 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 18338 if (!isDebuggable) { 18339 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0) { 18340 isDebuggable = true; 18341 } 18342 } 18343 if (isDebuggable) { 18344 Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check + "; reporting"); 18345 final ProcessRecord myProc = proc; 18346 final File heapdumpFile = DumpHeapProvider.getJavaFile(); 18347 mMemWatchDumpProcName = proc.processName; 18348 mMemWatchDumpFile = heapdumpFile.toString(); 18349 mMemWatchDumpPid = proc.pid; 18350 mMemWatchDumpUid = proc.uid; 18351 BackgroundThread.getHandler().post(new Runnable() { 18352 @Override 18353 public void run() { 18354 revokeUriPermission(ActivityThread.currentActivityThread() 18355 .getApplicationThread(), 18356 DumpHeapActivity.JAVA_URI, 18357 Intent.FLAG_GRANT_READ_URI_PERMISSION 18358 | Intent.FLAG_GRANT_WRITE_URI_PERMISSION, 18359 UserHandle.myUserId()); 18360 ParcelFileDescriptor fd = null; 18361 try { 18362 heapdumpFile.delete(); 18363 fd = ParcelFileDescriptor.open(heapdumpFile, 18364 ParcelFileDescriptor.MODE_CREATE | 18365 ParcelFileDescriptor.MODE_TRUNCATE | 18366 ParcelFileDescriptor.MODE_WRITE_ONLY | 18367 ParcelFileDescriptor.MODE_APPEND); 18368 IApplicationThread thread = myProc.thread; 18369 if (thread != null) { 18370 try { 18371 if (DEBUG_PSS) Slog.d(TAG_PSS, 18372 "Requesting dump heap from " 18373 + myProc + " to " + heapdumpFile); 18374 thread.dumpHeap(true, heapdumpFile.toString(), fd); 18375 } catch (RemoteException e) { 18376 } 18377 } 18378 } catch (FileNotFoundException e) { 18379 e.printStackTrace(); 18380 } finally { 18381 if (fd != null) { 18382 try { 18383 fd.close(); 18384 } catch (IOException e) { 18385 } 18386 } 18387 } 18388 } 18389 }); 18390 } else { 18391 Slog.w(TAG, "Process " + proc + " exceeded pss limit " + check 18392 + ", but debugging not enabled"); 18393 } 18394 } 18395 } 18396 } 18397 18398 /** 18399 * Schedule PSS collection of a process. 18400 */ requestPssLocked(ProcessRecord proc, int procState)18401 void requestPssLocked(ProcessRecord proc, int procState) { 18402 if (mPendingPssProcesses.contains(proc)) { 18403 return; 18404 } 18405 if (mPendingPssProcesses.size() == 0) { 18406 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 18407 } 18408 if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting PSS of: " + proc); 18409 proc.pssProcState = procState; 18410 mPendingPssProcesses.add(proc); 18411 } 18412 18413 /** 18414 * Schedule PSS collection of all processes. 18415 */ requestPssAllProcsLocked(long now, boolean always, boolean memLowered)18416 void requestPssAllProcsLocked(long now, boolean always, boolean memLowered) { 18417 if (!always) { 18418 if (now < (mLastFullPssTime + 18419 (memLowered ? FULL_PSS_LOWERED_INTERVAL : FULL_PSS_MIN_INTERVAL))) { 18420 return; 18421 } 18422 } 18423 if (DEBUG_PSS) Slog.d(TAG_PSS, "Requesting PSS of all procs! memLowered=" + memLowered); 18424 mLastFullPssTime = now; 18425 mFullPssPending = true; 18426 mPendingPssProcesses.ensureCapacity(mLruProcesses.size()); 18427 mPendingPssProcesses.clear(); 18428 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 18429 ProcessRecord app = mLruProcesses.get(i); 18430 if (app.thread == null 18431 || app.curProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) { 18432 continue; 18433 } 18434 if (memLowered || now > (app.lastStateTime+ProcessList.PSS_ALL_INTERVAL)) { 18435 app.pssProcState = app.setProcState; 18436 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true, 18437 mTestPssMode, isSleeping(), now); 18438 mPendingPssProcesses.add(app); 18439 } 18440 } 18441 mBgHandler.sendEmptyMessage(COLLECT_PSS_BG_MSG); 18442 } 18443 setTestPssMode(boolean enabled)18444 public void setTestPssMode(boolean enabled) { 18445 synchronized (this) { 18446 mTestPssMode = enabled; 18447 if (enabled) { 18448 // Whenever we enable the mode, we want to take a snapshot all of current 18449 // process mem use. 18450 requestPssAllProcsLocked(SystemClock.uptimeMillis(), true, true); 18451 } 18452 } 18453 } 18454 18455 /** 18456 * Ask a given process to GC right now. 18457 */ performAppGcLocked(ProcessRecord app)18458 final void performAppGcLocked(ProcessRecord app) { 18459 try { 18460 app.lastRequestedGc = SystemClock.uptimeMillis(); 18461 if (app.thread != null) { 18462 if (app.reportLowMemory) { 18463 app.reportLowMemory = false; 18464 app.thread.scheduleLowMemory(); 18465 } else { 18466 app.thread.processInBackground(); 18467 } 18468 } 18469 } catch (Exception e) { 18470 // whatever. 18471 } 18472 } 18473 18474 /** 18475 * Returns true if things are idle enough to perform GCs. 18476 */ canGcNowLocked()18477 private final boolean canGcNowLocked() { 18478 boolean processingBroadcasts = false; 18479 for (BroadcastQueue q : mBroadcastQueues) { 18480 if (q.mParallelBroadcasts.size() != 0 || q.mOrderedBroadcasts.size() != 0) { 18481 processingBroadcasts = true; 18482 } 18483 } 18484 return !processingBroadcasts 18485 && (isSleeping() || mStackSupervisor.allResumedActivitiesIdle()); 18486 } 18487 18488 /** 18489 * Perform GCs on all processes that are waiting for it, but only 18490 * if things are idle. 18491 */ performAppGcsLocked()18492 final void performAppGcsLocked() { 18493 final int N = mProcessesToGc.size(); 18494 if (N <= 0) { 18495 return; 18496 } 18497 if (canGcNowLocked()) { 18498 while (mProcessesToGc.size() > 0) { 18499 ProcessRecord proc = mProcessesToGc.remove(0); 18500 if (proc.curRawAdj > ProcessList.PERCEPTIBLE_APP_ADJ || proc.reportLowMemory) { 18501 if ((proc.lastRequestedGc+GC_MIN_INTERVAL) 18502 <= SystemClock.uptimeMillis()) { 18503 // To avoid spamming the system, we will GC processes one 18504 // at a time, waiting a few seconds between each. 18505 performAppGcLocked(proc); 18506 scheduleAppGcsLocked(); 18507 return; 18508 } else { 18509 // It hasn't been long enough since we last GCed this 18510 // process... put it in the list to wait for its time. 18511 addProcessToGcListLocked(proc); 18512 break; 18513 } 18514 } 18515 } 18516 18517 scheduleAppGcsLocked(); 18518 } 18519 } 18520 18521 /** 18522 * If all looks good, perform GCs on all processes waiting for them. 18523 */ performAppGcsIfAppropriateLocked()18524 final void performAppGcsIfAppropriateLocked() { 18525 if (canGcNowLocked()) { 18526 performAppGcsLocked(); 18527 return; 18528 } 18529 // Still not idle, wait some more. 18530 scheduleAppGcsLocked(); 18531 } 18532 18533 /** 18534 * Schedule the execution of all pending app GCs. 18535 */ scheduleAppGcsLocked()18536 final void scheduleAppGcsLocked() { 18537 mHandler.removeMessages(GC_BACKGROUND_PROCESSES_MSG); 18538 18539 if (mProcessesToGc.size() > 0) { 18540 // Schedule a GC for the time to the next process. 18541 ProcessRecord proc = mProcessesToGc.get(0); 18542 Message msg = mHandler.obtainMessage(GC_BACKGROUND_PROCESSES_MSG); 18543 18544 long when = proc.lastRequestedGc + GC_MIN_INTERVAL; 18545 long now = SystemClock.uptimeMillis(); 18546 if (when < (now+GC_TIMEOUT)) { 18547 when = now + GC_TIMEOUT; 18548 } 18549 mHandler.sendMessageAtTime(msg, when); 18550 } 18551 } 18552 18553 /** 18554 * Add a process to the array of processes waiting to be GCed. Keeps the 18555 * list in sorted order by the last GC time. The process can't already be 18556 * on the list. 18557 */ addProcessToGcListLocked(ProcessRecord proc)18558 final void addProcessToGcListLocked(ProcessRecord proc) { 18559 boolean added = false; 18560 for (int i=mProcessesToGc.size()-1; i>=0; i--) { 18561 if (mProcessesToGc.get(i).lastRequestedGc < 18562 proc.lastRequestedGc) { 18563 added = true; 18564 mProcessesToGc.add(i+1, proc); 18565 break; 18566 } 18567 } 18568 if (!added) { 18569 mProcessesToGc.add(0, proc); 18570 } 18571 } 18572 18573 /** 18574 * Set up to ask a process to GC itself. This will either do it 18575 * immediately, or put it on the list of processes to gc the next 18576 * time things are idle. 18577 */ scheduleAppGcLocked(ProcessRecord app)18578 final void scheduleAppGcLocked(ProcessRecord app) { 18579 long now = SystemClock.uptimeMillis(); 18580 if ((app.lastRequestedGc+GC_MIN_INTERVAL) > now) { 18581 return; 18582 } 18583 if (!mProcessesToGc.contains(app)) { 18584 addProcessToGcListLocked(app); 18585 scheduleAppGcsLocked(); 18586 } 18587 } 18588 checkExcessivePowerUsageLocked(boolean doKills)18589 final void checkExcessivePowerUsageLocked(boolean doKills) { 18590 updateCpuStatsNow(); 18591 18592 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 18593 boolean doWakeKills = doKills; 18594 boolean doCpuKills = doKills; 18595 if (mLastPowerCheckRealtime == 0) { 18596 doWakeKills = false; 18597 } 18598 if (mLastPowerCheckUptime == 0) { 18599 doCpuKills = false; 18600 } 18601 if (stats.isScreenOn()) { 18602 doWakeKills = false; 18603 } 18604 final long curRealtime = SystemClock.elapsedRealtime(); 18605 final long realtimeSince = curRealtime - mLastPowerCheckRealtime; 18606 final long curUptime = SystemClock.uptimeMillis(); 18607 final long uptimeSince = curUptime - mLastPowerCheckUptime; 18608 mLastPowerCheckRealtime = curRealtime; 18609 mLastPowerCheckUptime = curUptime; 18610 if (realtimeSince < WAKE_LOCK_MIN_CHECK_DURATION) { 18611 doWakeKills = false; 18612 } 18613 if (uptimeSince < CPU_MIN_CHECK_DURATION) { 18614 doCpuKills = false; 18615 } 18616 int i = mLruProcesses.size(); 18617 while (i > 0) { 18618 i--; 18619 ProcessRecord app = mLruProcesses.get(i); 18620 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 18621 long wtime; 18622 synchronized (stats) { 18623 wtime = stats.getProcessWakeTime(app.info.uid, 18624 app.pid, curRealtime); 18625 } 18626 long wtimeUsed = wtime - app.lastWakeTime; 18627 long cputimeUsed = app.curCpuTime - app.lastCpuTime; 18628 if (DEBUG_POWER) { 18629 StringBuilder sb = new StringBuilder(128); 18630 sb.append("Wake for "); 18631 app.toShortString(sb); 18632 sb.append(": over "); 18633 TimeUtils.formatDuration(realtimeSince, sb); 18634 sb.append(" used "); 18635 TimeUtils.formatDuration(wtimeUsed, sb); 18636 sb.append(" ("); 18637 sb.append((wtimeUsed*100)/realtimeSince); 18638 sb.append("%)"); 18639 Slog.i(TAG_POWER, sb.toString()); 18640 sb.setLength(0); 18641 sb.append("CPU for "); 18642 app.toShortString(sb); 18643 sb.append(": over "); 18644 TimeUtils.formatDuration(uptimeSince, sb); 18645 sb.append(" used "); 18646 TimeUtils.formatDuration(cputimeUsed, sb); 18647 sb.append(" ("); 18648 sb.append((cputimeUsed*100)/uptimeSince); 18649 sb.append("%)"); 18650 Slog.i(TAG_POWER, sb.toString()); 18651 } 18652 // If a process has held a wake lock for more 18653 // than 50% of the time during this period, 18654 // that sounds bad. Kill! 18655 if (doWakeKills && realtimeSince > 0 18656 && ((wtimeUsed*100)/realtimeSince) >= 50) { 18657 synchronized (stats) { 18658 stats.reportExcessiveWakeLocked(app.info.uid, app.processName, 18659 realtimeSince, wtimeUsed); 18660 } 18661 app.kill("excessive wake held " + wtimeUsed + " during " + realtimeSince, true); 18662 app.baseProcessTracker.reportExcessiveWake(app.pkgList); 18663 } else if (doCpuKills && uptimeSince > 0 18664 && ((cputimeUsed*100)/uptimeSince) >= 25) { 18665 synchronized (stats) { 18666 stats.reportExcessiveCpuLocked(app.info.uid, app.processName, 18667 uptimeSince, cputimeUsed); 18668 } 18669 app.kill("excessive cpu " + cputimeUsed + " during " + uptimeSince, true); 18670 app.baseProcessTracker.reportExcessiveCpu(app.pkgList); 18671 } else { 18672 app.lastWakeTime = wtime; 18673 app.lastCpuTime = app.curCpuTime; 18674 } 18675 } 18676 } 18677 } 18678 applyOomAdjLocked(ProcessRecord app, boolean doingAll, long now, long nowElapsed)18679 private final boolean applyOomAdjLocked(ProcessRecord app, boolean doingAll, long now, 18680 long nowElapsed) { 18681 boolean success = true; 18682 18683 if (app.curRawAdj != app.setRawAdj) { 18684 app.setRawAdj = app.curRawAdj; 18685 } 18686 18687 int changes = 0; 18688 18689 if (app.curAdj != app.setAdj) { 18690 ProcessList.setOomAdj(app.pid, app.info.uid, app.curAdj); 18691 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 18692 "Set " + app.pid + " " + app.processName + " adj " + app.curAdj + ": " 18693 + app.adjType); 18694 app.setAdj = app.curAdj; 18695 } 18696 18697 if (app.setSchedGroup != app.curSchedGroup) { 18698 app.setSchedGroup = app.curSchedGroup; 18699 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 18700 "Setting process group of " + app.processName 18701 + " to " + app.curSchedGroup); 18702 if (app.waitingToKill != null && app.curReceiver == null 18703 && app.setSchedGroup == Process.THREAD_GROUP_BG_NONINTERACTIVE) { 18704 app.kill(app.waitingToKill, true); 18705 success = false; 18706 } else { 18707 if (true) { 18708 long oldId = Binder.clearCallingIdentity(); 18709 try { 18710 Process.setProcessGroup(app.pid, app.curSchedGroup); 18711 } catch (Exception e) { 18712 Slog.w(TAG, "Failed setting process group of " + app.pid 18713 + " to " + app.curSchedGroup); 18714 e.printStackTrace(); 18715 } finally { 18716 Binder.restoreCallingIdentity(oldId); 18717 } 18718 } else { 18719 if (app.thread != null) { 18720 try { 18721 app.thread.setSchedulingGroup(app.curSchedGroup); 18722 } catch (RemoteException e) { 18723 } 18724 } 18725 } 18726 Process.setSwappiness(app.pid, 18727 app.curSchedGroup <= Process.THREAD_GROUP_BG_NONINTERACTIVE); 18728 } 18729 } 18730 if (app.repForegroundActivities != app.foregroundActivities) { 18731 app.repForegroundActivities = app.foregroundActivities; 18732 changes |= ProcessChangeItem.CHANGE_ACTIVITIES; 18733 } 18734 if (app.repProcState != app.curProcState) { 18735 app.repProcState = app.curProcState; 18736 changes |= ProcessChangeItem.CHANGE_PROCESS_STATE; 18737 if (app.thread != null) { 18738 try { 18739 if (false) { 18740 //RuntimeException h = new RuntimeException("here"); 18741 Slog.i(TAG, "Sending new process state " + app.repProcState 18742 + " to " + app /*, h*/); 18743 } 18744 app.thread.setProcessState(app.repProcState); 18745 } catch (RemoteException e) { 18746 } 18747 } 18748 } 18749 if (app.setProcState == ActivityManager.PROCESS_STATE_NONEXISTENT 18750 || ProcessList.procStatesDifferForMem(app.curProcState, app.setProcState)) { 18751 if (false && mTestPssMode && app.setProcState >= 0 && app.lastStateTime <= (now-200)) { 18752 // Experimental code to more aggressively collect pss while 18753 // running test... the problem is that this tends to collect 18754 // the data right when a process is transitioning between process 18755 // states, which well tend to give noisy data. 18756 long start = SystemClock.uptimeMillis(); 18757 long pss = Debug.getPss(app.pid, mTmpLong, null); 18758 recordPssSampleLocked(app, app.curProcState, pss, mTmpLong[0], now); 18759 mPendingPssProcesses.remove(app); 18760 Slog.i(TAG, "Recorded pss for " + app + " state " + app.setProcState 18761 + " to " + app.curProcState + ": " 18762 + (SystemClock.uptimeMillis()-start) + "ms"); 18763 } 18764 app.lastStateTime = now; 18765 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, true, 18766 mTestPssMode, isSleeping(), now); 18767 if (DEBUG_PSS) Slog.d(TAG_PSS, "Process state change from " 18768 + ProcessList.makeProcStateString(app.setProcState) + " to " 18769 + ProcessList.makeProcStateString(app.curProcState) + " next pss in " 18770 + (app.nextPssTime-now) + ": " + app); 18771 } else { 18772 if (now > app.nextPssTime || (now > (app.lastPssTime+ProcessList.PSS_MAX_INTERVAL) 18773 && now > (app.lastStateTime+ProcessList.minTimeFromStateChange( 18774 mTestPssMode)))) { 18775 requestPssLocked(app, app.setProcState); 18776 app.nextPssTime = ProcessList.computeNextPssTime(app.curProcState, false, 18777 mTestPssMode, isSleeping(), now); 18778 } else if (false && DEBUG_PSS) Slog.d(TAG_PSS, 18779 "Not requesting PSS of " + app + ": next=" + (app.nextPssTime-now)); 18780 } 18781 if (app.setProcState != app.curProcState) { 18782 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 18783 "Proc state change of " + app.processName 18784 + " to " + app.curProcState); 18785 boolean setImportant = app.setProcState < ActivityManager.PROCESS_STATE_SERVICE; 18786 boolean curImportant = app.curProcState < ActivityManager.PROCESS_STATE_SERVICE; 18787 if (setImportant && !curImportant) { 18788 // This app is no longer something we consider important enough to allow to 18789 // use arbitrary amounts of battery power. Note 18790 // its current wake lock time to later know to kill it if 18791 // it is not behaving well. 18792 BatteryStatsImpl stats = mBatteryStatsService.getActiveStatistics(); 18793 synchronized (stats) { 18794 app.lastWakeTime = stats.getProcessWakeTime(app.info.uid, 18795 app.pid, nowElapsed); 18796 } 18797 app.lastCpuTime = app.curCpuTime; 18798 18799 } 18800 // Inform UsageStats of important process state change 18801 // Must be called before updating setProcState 18802 maybeUpdateUsageStatsLocked(app, nowElapsed); 18803 18804 app.setProcState = app.curProcState; 18805 if (app.setProcState >= ActivityManager.PROCESS_STATE_HOME) { 18806 app.notCachedSinceIdle = false; 18807 } 18808 if (!doingAll) { 18809 setProcessTrackerStateLocked(app, mProcessStats.getMemFactorLocked(), now); 18810 } else { 18811 app.procStateChanged = true; 18812 } 18813 } else if (app.reportedInteraction && (nowElapsed-app.interactionEventTime) 18814 > USAGE_STATS_INTERACTION_INTERVAL) { 18815 // For apps that sit around for a long time in the interactive state, we need 18816 // to report this at least once a day so they don't go idle. 18817 maybeUpdateUsageStatsLocked(app, nowElapsed); 18818 } 18819 18820 if (changes != 0) { 18821 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 18822 "Changes in " + app + ": " + changes); 18823 int i = mPendingProcessChanges.size()-1; 18824 ProcessChangeItem item = null; 18825 while (i >= 0) { 18826 item = mPendingProcessChanges.get(i); 18827 if (item.pid == app.pid) { 18828 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 18829 "Re-using existing item: " + item); 18830 break; 18831 } 18832 i--; 18833 } 18834 if (i < 0) { 18835 // No existing item in pending changes; need a new one. 18836 final int NA = mAvailProcessChanges.size(); 18837 if (NA > 0) { 18838 item = mAvailProcessChanges.remove(NA-1); 18839 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 18840 "Retrieving available item: " + item); 18841 } else { 18842 item = new ProcessChangeItem(); 18843 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 18844 "Allocating new item: " + item); 18845 } 18846 item.changes = 0; 18847 item.pid = app.pid; 18848 item.uid = app.info.uid; 18849 if (mPendingProcessChanges.size() == 0) { 18850 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 18851 "*** Enqueueing dispatch processes changed!"); 18852 mUiHandler.obtainMessage(DISPATCH_PROCESSES_CHANGED).sendToTarget(); 18853 } 18854 mPendingProcessChanges.add(item); 18855 } 18856 item.changes |= changes; 18857 item.processState = app.repProcState; 18858 item.foregroundActivities = app.repForegroundActivities; 18859 if (DEBUG_PROCESS_OBSERVERS) Slog.i(TAG_PROCESS_OBSERVERS, 18860 "Item " + Integer.toHexString(System.identityHashCode(item)) 18861 + " " + app.toShortString() + ": changes=" + item.changes 18862 + " procState=" + item.processState 18863 + " foreground=" + item.foregroundActivities 18864 + " type=" + app.adjType + " source=" + app.adjSource 18865 + " target=" + app.adjTarget); 18866 } 18867 18868 return success; 18869 } 18870 enqueueUidChangeLocked(UidRecord uidRec, boolean gone)18871 private final void enqueueUidChangeLocked(UidRecord uidRec, boolean gone) { 18872 if (uidRec.pendingChange == null) { 18873 if (mPendingUidChanges.size() == 0) { 18874 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 18875 "*** Enqueueing dispatch uid changed!"); 18876 mUiHandler.obtainMessage(DISPATCH_UIDS_CHANGED_MSG).sendToTarget(); 18877 } 18878 final int NA = mAvailUidChanges.size(); 18879 if (NA > 0) { 18880 uidRec.pendingChange = mAvailUidChanges.remove(NA-1); 18881 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 18882 "Retrieving available item: " + uidRec.pendingChange); 18883 } else { 18884 uidRec.pendingChange = new UidRecord.ChangeItem(); 18885 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 18886 "Allocating new item: " + uidRec.pendingChange); 18887 } 18888 uidRec.pendingChange.uidRecord = uidRec; 18889 uidRec.pendingChange.uid = uidRec.uid; 18890 mPendingUidChanges.add(uidRec.pendingChange); 18891 } 18892 uidRec.pendingChange.gone = gone; 18893 uidRec.pendingChange.processState = uidRec.setProcState; 18894 } 18895 maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, String authority)18896 private void maybeUpdateProviderUsageStatsLocked(ProcessRecord app, String providerPkgName, 18897 String authority) { 18898 if (app == null) return; 18899 if (app.curProcState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) { 18900 UserState userState = mStartedUsers.get(app.userId); 18901 if (userState == null) return; 18902 final long now = SystemClock.elapsedRealtime(); 18903 Long lastReported = userState.mProviderLastReportedFg.get(authority); 18904 if (lastReported == null || lastReported < now - 60 * 1000L) { 18905 mUsageStatsService.reportContentProviderUsage( 18906 authority, providerPkgName, app.userId); 18907 userState.mProviderLastReportedFg.put(authority, now); 18908 } 18909 } 18910 } 18911 maybeUpdateUsageStatsLocked(ProcessRecord app, long nowElapsed)18912 private void maybeUpdateUsageStatsLocked(ProcessRecord app, long nowElapsed) { 18913 if (DEBUG_USAGE_STATS) { 18914 Slog.d(TAG, "Checking proc [" + Arrays.toString(app.getPackageList()) 18915 + "] state changes: old = " + app.setProcState + ", new = " 18916 + app.curProcState); 18917 } 18918 if (mUsageStatsService == null) { 18919 return; 18920 } 18921 boolean isInteraction; 18922 // To avoid some abuse patterns, we are going to be careful about what we consider 18923 // to be an app interaction. Being the top activity doesn't count while the display 18924 // is sleeping, nor do short foreground services. 18925 if (app.curProcState <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) { 18926 isInteraction = true; 18927 app.fgInteractionTime = 0; 18928 } else if (app.curProcState <= ActivityManager.PROCESS_STATE_TOP_SLEEPING) { 18929 if (app.fgInteractionTime == 0) { 18930 app.fgInteractionTime = nowElapsed; 18931 isInteraction = false; 18932 } else { 18933 isInteraction = nowElapsed > app.fgInteractionTime + SERVICE_USAGE_INTERACTION_TIME; 18934 } 18935 } else { 18936 isInteraction = app.curProcState 18937 <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND; 18938 app.fgInteractionTime = 0; 18939 } 18940 if (isInteraction && (!app.reportedInteraction 18941 || (nowElapsed-app.interactionEventTime) > USAGE_STATS_INTERACTION_INTERVAL)) { 18942 app.interactionEventTime = nowElapsed; 18943 String[] packages = app.getPackageList(); 18944 if (packages != null) { 18945 for (int i = 0; i < packages.length; i++) { 18946 mUsageStatsService.reportEvent(packages[i], app.userId, 18947 UsageEvents.Event.SYSTEM_INTERACTION); 18948 } 18949 } 18950 } 18951 app.reportedInteraction = isInteraction; 18952 if (!isInteraction) { 18953 app.interactionEventTime = 0; 18954 } 18955 } 18956 setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now)18957 private final void setProcessTrackerStateLocked(ProcessRecord proc, int memFactor, long now) { 18958 if (proc.thread != null) { 18959 if (proc.baseProcessTracker != null) { 18960 proc.baseProcessTracker.setState(proc.repProcState, memFactor, now, proc.pkgList); 18961 } 18962 if (proc.repProcState >= 0) { 18963 mBatteryStatsService.noteProcessState(proc.processName, proc.info.uid, 18964 proc.repProcState); 18965 } 18966 } 18967 } 18968 updateOomAdjLocked(ProcessRecord app, int cachedAdj, ProcessRecord TOP_APP, boolean doingAll, long now)18969 private final boolean updateOomAdjLocked(ProcessRecord app, int cachedAdj, 18970 ProcessRecord TOP_APP, boolean doingAll, long now) { 18971 if (app.thread == null) { 18972 return false; 18973 } 18974 18975 computeOomAdjLocked(app, cachedAdj, TOP_APP, doingAll, now); 18976 18977 return applyOomAdjLocked(app, doingAll, now, SystemClock.elapsedRealtime()); 18978 } 18979 updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, boolean oomAdj)18980 final void updateProcessForegroundLocked(ProcessRecord proc, boolean isForeground, 18981 boolean oomAdj) { 18982 if (isForeground != proc.foregroundServices) { 18983 proc.foregroundServices = isForeground; 18984 ArrayList<ProcessRecord> curProcs = mForegroundPackages.get(proc.info.packageName, 18985 proc.info.uid); 18986 if (isForeground) { 18987 if (curProcs == null) { 18988 curProcs = new ArrayList<ProcessRecord>(); 18989 mForegroundPackages.put(proc.info.packageName, proc.info.uid, curProcs); 18990 } 18991 if (!curProcs.contains(proc)) { 18992 curProcs.add(proc); 18993 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_FOREGROUND_START, 18994 proc.info.packageName, proc.info.uid); 18995 } 18996 } else { 18997 if (curProcs != null) { 18998 if (curProcs.remove(proc)) { 18999 mBatteryStatsService.noteEvent( 19000 BatteryStats.HistoryItem.EVENT_FOREGROUND_FINISH, 19001 proc.info.packageName, proc.info.uid); 19002 if (curProcs.size() <= 0) { 19003 mForegroundPackages.remove(proc.info.packageName, proc.info.uid); 19004 } 19005 } 19006 } 19007 } 19008 if (oomAdj) { 19009 updateOomAdjLocked(); 19010 } 19011 } 19012 } 19013 resumedAppLocked()19014 private final ActivityRecord resumedAppLocked() { 19015 ActivityRecord act = mStackSupervisor.resumedAppLocked(); 19016 String pkg; 19017 int uid; 19018 if (act != null) { 19019 pkg = act.packageName; 19020 uid = act.info.applicationInfo.uid; 19021 } else { 19022 pkg = null; 19023 uid = -1; 19024 } 19025 // Has the UID or resumed package name changed? 19026 if (uid != mCurResumedUid || (pkg != mCurResumedPackage 19027 && (pkg == null || !pkg.equals(mCurResumedPackage)))) { 19028 if (mCurResumedPackage != null) { 19029 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_FINISH, 19030 mCurResumedPackage, mCurResumedUid); 19031 } 19032 mCurResumedPackage = pkg; 19033 mCurResumedUid = uid; 19034 if (mCurResumedPackage != null) { 19035 mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_TOP_START, 19036 mCurResumedPackage, mCurResumedUid); 19037 } 19038 } 19039 return act; 19040 } 19041 updateOomAdjLocked(ProcessRecord app)19042 final boolean updateOomAdjLocked(ProcessRecord app) { 19043 final ActivityRecord TOP_ACT = resumedAppLocked(); 19044 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null; 19045 final boolean wasCached = app.cached; 19046 19047 mAdjSeq++; 19048 19049 // This is the desired cached adjusment we want to tell it to use. 19050 // If our app is currently cached, we know it, and that is it. Otherwise, 19051 // we don't know it yet, and it needs to now be cached we will then 19052 // need to do a complete oom adj. 19053 final int cachedAdj = app.curRawAdj >= ProcessList.CACHED_APP_MIN_ADJ 19054 ? app.curRawAdj : ProcessList.UNKNOWN_ADJ; 19055 boolean success = updateOomAdjLocked(app, cachedAdj, TOP_APP, false, 19056 SystemClock.uptimeMillis()); 19057 if (wasCached != app.cached || app.curRawAdj == ProcessList.UNKNOWN_ADJ) { 19058 // Changed to/from cached state, so apps after it in the LRU 19059 // list may also be changed. 19060 updateOomAdjLocked(); 19061 } 19062 return success; 19063 } 19064 updateOomAdjLocked()19065 final void updateOomAdjLocked() { 19066 final ActivityRecord TOP_ACT = resumedAppLocked(); 19067 final ProcessRecord TOP_APP = TOP_ACT != null ? TOP_ACT.app : null; 19068 final long now = SystemClock.uptimeMillis(); 19069 final long nowElapsed = SystemClock.elapsedRealtime(); 19070 final long oldTime = now - ProcessList.MAX_EMPTY_TIME; 19071 final int N = mLruProcesses.size(); 19072 19073 if (false) { 19074 RuntimeException e = new RuntimeException(); 19075 e.fillInStackTrace(); 19076 Slog.i(TAG, "updateOomAdj: top=" + TOP_ACT, e); 19077 } 19078 19079 // Reset state in all uid records. 19080 for (int i=mActiveUids.size()-1; i>=0; i--) { 19081 final UidRecord uidRec = mActiveUids.valueAt(i); 19082 if (false && DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 19083 "Starting update of " + uidRec); 19084 uidRec.reset(); 19085 } 19086 19087 mAdjSeq++; 19088 mNewNumServiceProcs = 0; 19089 mNewNumAServiceProcs = 0; 19090 19091 final int emptyProcessLimit; 19092 final int cachedProcessLimit; 19093 if (mProcessLimit <= 0) { 19094 emptyProcessLimit = cachedProcessLimit = 0; 19095 } else if (mProcessLimit == 1) { 19096 emptyProcessLimit = 1; 19097 cachedProcessLimit = 0; 19098 } else { 19099 emptyProcessLimit = ProcessList.computeEmptyProcessLimit(mProcessLimit); 19100 cachedProcessLimit = mProcessLimit - emptyProcessLimit; 19101 } 19102 19103 // Let's determine how many processes we have running vs. 19104 // how many slots we have for background processes; we may want 19105 // to put multiple processes in a slot of there are enough of 19106 // them. 19107 int numSlots = (ProcessList.CACHED_APP_MAX_ADJ 19108 - ProcessList.CACHED_APP_MIN_ADJ + 1) / 2; 19109 int numEmptyProcs = N - mNumNonCachedProcs - mNumCachedHiddenProcs; 19110 if (numEmptyProcs > cachedProcessLimit) { 19111 // If there are more empty processes than our limit on cached 19112 // processes, then use the cached process limit for the factor. 19113 // This ensures that the really old empty processes get pushed 19114 // down to the bottom, so if we are running low on memory we will 19115 // have a better chance at keeping around more cached processes 19116 // instead of a gazillion empty processes. 19117 numEmptyProcs = cachedProcessLimit; 19118 } 19119 int emptyFactor = numEmptyProcs/numSlots; 19120 if (emptyFactor < 1) emptyFactor = 1; 19121 int cachedFactor = (mNumCachedHiddenProcs > 0 ? mNumCachedHiddenProcs : 1)/numSlots; 19122 if (cachedFactor < 1) cachedFactor = 1; 19123 int stepCached = 0; 19124 int stepEmpty = 0; 19125 int numCached = 0; 19126 int numEmpty = 0; 19127 int numTrimming = 0; 19128 19129 mNumNonCachedProcs = 0; 19130 mNumCachedHiddenProcs = 0; 19131 19132 // First update the OOM adjustment for each of the 19133 // application processes based on their current state. 19134 int curCachedAdj = ProcessList.CACHED_APP_MIN_ADJ; 19135 int nextCachedAdj = curCachedAdj+1; 19136 int curEmptyAdj = ProcessList.CACHED_APP_MIN_ADJ; 19137 int nextEmptyAdj = curEmptyAdj+2; 19138 for (int i=N-1; i>=0; i--) { 19139 ProcessRecord app = mLruProcesses.get(i); 19140 if (!app.killedByAm && app.thread != null) { 19141 app.procStateChanged = false; 19142 computeOomAdjLocked(app, ProcessList.UNKNOWN_ADJ, TOP_APP, true, now); 19143 19144 // If we haven't yet assigned the final cached adj 19145 // to the process, do that now. 19146 if (app.curAdj >= ProcessList.UNKNOWN_ADJ) { 19147 switch (app.curProcState) { 19148 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 19149 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 19150 // This process is a cached process holding activities... 19151 // assign it the next cached value for that type, and then 19152 // step that cached level. 19153 app.curRawAdj = curCachedAdj; 19154 app.curAdj = app.modifyRawOomAdj(curCachedAdj); 19155 if (DEBUG_LRU && false) Slog.d(TAG_LRU, "Assigning activity LRU #" + i 19156 + " adj: " + app.curAdj + " (curCachedAdj=" + curCachedAdj 19157 + ")"); 19158 if (curCachedAdj != nextCachedAdj) { 19159 stepCached++; 19160 if (stepCached >= cachedFactor) { 19161 stepCached = 0; 19162 curCachedAdj = nextCachedAdj; 19163 nextCachedAdj += 2; 19164 if (nextCachedAdj > ProcessList.CACHED_APP_MAX_ADJ) { 19165 nextCachedAdj = ProcessList.CACHED_APP_MAX_ADJ; 19166 } 19167 } 19168 } 19169 break; 19170 default: 19171 // For everything else, assign next empty cached process 19172 // level and bump that up. Note that this means that 19173 // long-running services that have dropped down to the 19174 // cached level will be treated as empty (since their process 19175 // state is still as a service), which is what we want. 19176 app.curRawAdj = curEmptyAdj; 19177 app.curAdj = app.modifyRawOomAdj(curEmptyAdj); 19178 if (DEBUG_LRU && false) Slog.d(TAG_LRU, "Assigning empty LRU #" + i 19179 + " adj: " + app.curAdj + " (curEmptyAdj=" + curEmptyAdj 19180 + ")"); 19181 if (curEmptyAdj != nextEmptyAdj) { 19182 stepEmpty++; 19183 if (stepEmpty >= emptyFactor) { 19184 stepEmpty = 0; 19185 curEmptyAdj = nextEmptyAdj; 19186 nextEmptyAdj += 2; 19187 if (nextEmptyAdj > ProcessList.CACHED_APP_MAX_ADJ) { 19188 nextEmptyAdj = ProcessList.CACHED_APP_MAX_ADJ; 19189 } 19190 } 19191 } 19192 break; 19193 } 19194 } 19195 19196 applyOomAdjLocked(app, true, now, nowElapsed); 19197 19198 // Count the number of process types. 19199 switch (app.curProcState) { 19200 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY: 19201 case ActivityManager.PROCESS_STATE_CACHED_ACTIVITY_CLIENT: 19202 mNumCachedHiddenProcs++; 19203 numCached++; 19204 if (numCached > cachedProcessLimit) { 19205 app.kill("cached #" + numCached, true); 19206 } 19207 break; 19208 case ActivityManager.PROCESS_STATE_CACHED_EMPTY: 19209 if (numEmpty > ProcessList.TRIM_EMPTY_APPS 19210 && app.lastActivityTime < oldTime) { 19211 app.kill("empty for " 19212 + ((oldTime + ProcessList.MAX_EMPTY_TIME - app.lastActivityTime) 19213 / 1000) + "s", true); 19214 } else { 19215 numEmpty++; 19216 if (numEmpty > emptyProcessLimit) { 19217 app.kill("empty #" + numEmpty, true); 19218 } 19219 } 19220 break; 19221 default: 19222 mNumNonCachedProcs++; 19223 break; 19224 } 19225 19226 if (app.isolated && app.services.size() <= 0) { 19227 // If this is an isolated process, and there are no 19228 // services running in it, then the process is no longer 19229 // needed. We agressively kill these because we can by 19230 // definition not re-use the same process again, and it is 19231 // good to avoid having whatever code was running in them 19232 // left sitting around after no longer needed. 19233 app.kill("isolated not needed", true); 19234 } else { 19235 // Keeping this process, update its uid. 19236 final UidRecord uidRec = app.uidRecord; 19237 if (uidRec != null && uidRec.curProcState > app.curProcState) { 19238 uidRec.curProcState = app.curProcState; 19239 } 19240 } 19241 19242 if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME 19243 && !app.killedByAm) { 19244 numTrimming++; 19245 } 19246 } 19247 } 19248 19249 mNumServiceProcs = mNewNumServiceProcs; 19250 19251 // Now determine the memory trimming level of background processes. 19252 // Unfortunately we need to start at the back of the list to do this 19253 // properly. We only do this if the number of background apps we 19254 // are managing to keep around is less than half the maximum we desire; 19255 // if we are keeping a good number around, we'll let them use whatever 19256 // memory they want. 19257 final int numCachedAndEmpty = numCached + numEmpty; 19258 int memFactor; 19259 if (numCached <= ProcessList.TRIM_CACHED_APPS 19260 && numEmpty <= ProcessList.TRIM_EMPTY_APPS) { 19261 if (numCachedAndEmpty <= ProcessList.TRIM_CRITICAL_THRESHOLD) { 19262 memFactor = ProcessStats.ADJ_MEM_FACTOR_CRITICAL; 19263 } else if (numCachedAndEmpty <= ProcessList.TRIM_LOW_THRESHOLD) { 19264 memFactor = ProcessStats.ADJ_MEM_FACTOR_LOW; 19265 } else { 19266 memFactor = ProcessStats.ADJ_MEM_FACTOR_MODERATE; 19267 } 19268 } else { 19269 memFactor = ProcessStats.ADJ_MEM_FACTOR_NORMAL; 19270 } 19271 // We always allow the memory level to go up (better). We only allow it to go 19272 // down if we are in a state where that is allowed, *and* the total number of processes 19273 // has gone down since last time. 19274 if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "oom: memFactor=" + memFactor 19275 + " last=" + mLastMemoryLevel + " allowLow=" + mAllowLowerMemLevel 19276 + " numProcs=" + mLruProcesses.size() + " last=" + mLastNumProcesses); 19277 if (memFactor > mLastMemoryLevel) { 19278 if (!mAllowLowerMemLevel || mLruProcesses.size() >= mLastNumProcesses) { 19279 memFactor = mLastMemoryLevel; 19280 if (DEBUG_OOM_ADJ) Slog.d(TAG_OOM_ADJ, "Keeping last mem factor!"); 19281 } 19282 } 19283 mLastMemoryLevel = memFactor; 19284 mLastNumProcesses = mLruProcesses.size(); 19285 boolean allChanged = mProcessStats.setMemFactorLocked(memFactor, !isSleeping(), now); 19286 final int trackerMemFactor = mProcessStats.getMemFactorLocked(); 19287 if (memFactor != ProcessStats.ADJ_MEM_FACTOR_NORMAL) { 19288 if (mLowRamStartTime == 0) { 19289 mLowRamStartTime = now; 19290 } 19291 int step = 0; 19292 int fgTrimLevel; 19293 switch (memFactor) { 19294 case ProcessStats.ADJ_MEM_FACTOR_CRITICAL: 19295 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_CRITICAL; 19296 break; 19297 case ProcessStats.ADJ_MEM_FACTOR_LOW: 19298 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_LOW; 19299 break; 19300 default: 19301 fgTrimLevel = ComponentCallbacks2.TRIM_MEMORY_RUNNING_MODERATE; 19302 break; 19303 } 19304 int factor = numTrimming/3; 19305 int minFactor = 2; 19306 if (mHomeProcess != null) minFactor++; 19307 if (mPreviousProcess != null) minFactor++; 19308 if (factor < minFactor) factor = minFactor; 19309 int curLevel = ComponentCallbacks2.TRIM_MEMORY_COMPLETE; 19310 for (int i=N-1; i>=0; i--) { 19311 ProcessRecord app = mLruProcesses.get(i); 19312 if (allChanged || app.procStateChanged) { 19313 setProcessTrackerStateLocked(app, trackerMemFactor, now); 19314 app.procStateChanged = false; 19315 } 19316 if (app.curProcState >= ActivityManager.PROCESS_STATE_HOME 19317 && !app.killedByAm) { 19318 if (app.trimMemoryLevel < curLevel && app.thread != null) { 19319 try { 19320 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 19321 "Trimming memory of " + app.processName + " to " + curLevel); 19322 app.thread.scheduleTrimMemory(curLevel); 19323 } catch (RemoteException e) { 19324 } 19325 if (false) { 19326 // For now we won't do this; our memory trimming seems 19327 // to be good enough at this point that destroying 19328 // activities causes more harm than good. 19329 if (curLevel >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE 19330 && app != mHomeProcess && app != mPreviousProcess) { 19331 // Need to do this on its own message because the stack may not 19332 // be in a consistent state at this point. 19333 // For these apps we will also finish their activities 19334 // to help them free memory. 19335 mStackSupervisor.scheduleDestroyAllActivities(app, "trim"); 19336 } 19337 } 19338 } 19339 app.trimMemoryLevel = curLevel; 19340 step++; 19341 if (step >= factor) { 19342 step = 0; 19343 switch (curLevel) { 19344 case ComponentCallbacks2.TRIM_MEMORY_COMPLETE: 19345 curLevel = ComponentCallbacks2.TRIM_MEMORY_MODERATE; 19346 break; 19347 case ComponentCallbacks2.TRIM_MEMORY_MODERATE: 19348 curLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 19349 break; 19350 } 19351 } 19352 } else if (app.curProcState == ActivityManager.PROCESS_STATE_HEAVY_WEIGHT) { 19353 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_BACKGROUND 19354 && app.thread != null) { 19355 try { 19356 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 19357 "Trimming memory of heavy-weight " + app.processName 19358 + " to " + ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 19359 app.thread.scheduleTrimMemory( 19360 ComponentCallbacks2.TRIM_MEMORY_BACKGROUND); 19361 } catch (RemoteException e) { 19362 } 19363 } 19364 app.trimMemoryLevel = ComponentCallbacks2.TRIM_MEMORY_BACKGROUND; 19365 } else { 19366 if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 19367 || app.systemNoUi) && app.pendingUiClean) { 19368 // If this application is now in the background and it 19369 // had done UI, then give it the special trim level to 19370 // have it free UI resources. 19371 final int level = ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN; 19372 if (app.trimMemoryLevel < level && app.thread != null) { 19373 try { 19374 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 19375 "Trimming memory of bg-ui " + app.processName 19376 + " to " + level); 19377 app.thread.scheduleTrimMemory(level); 19378 } catch (RemoteException e) { 19379 } 19380 } 19381 app.pendingUiClean = false; 19382 } 19383 if (app.trimMemoryLevel < fgTrimLevel && app.thread != null) { 19384 try { 19385 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 19386 "Trimming memory of fg " + app.processName 19387 + " to " + fgTrimLevel); 19388 app.thread.scheduleTrimMemory(fgTrimLevel); 19389 } catch (RemoteException e) { 19390 } 19391 } 19392 app.trimMemoryLevel = fgTrimLevel; 19393 } 19394 } 19395 } else { 19396 if (mLowRamStartTime != 0) { 19397 mLowRamTimeSinceLastIdle += now - mLowRamStartTime; 19398 mLowRamStartTime = 0; 19399 } 19400 for (int i=N-1; i>=0; i--) { 19401 ProcessRecord app = mLruProcesses.get(i); 19402 if (allChanged || app.procStateChanged) { 19403 setProcessTrackerStateLocked(app, trackerMemFactor, now); 19404 app.procStateChanged = false; 19405 } 19406 if ((app.curProcState >= ActivityManager.PROCESS_STATE_IMPORTANT_BACKGROUND 19407 || app.systemNoUi) && app.pendingUiClean) { 19408 if (app.trimMemoryLevel < ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN 19409 && app.thread != null) { 19410 try { 19411 if (DEBUG_SWITCH || DEBUG_OOM_ADJ) Slog.v(TAG_OOM_ADJ, 19412 "Trimming memory of ui hidden " + app.processName 19413 + " to " + ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 19414 app.thread.scheduleTrimMemory( 19415 ComponentCallbacks2.TRIM_MEMORY_UI_HIDDEN); 19416 } catch (RemoteException e) { 19417 } 19418 } 19419 app.pendingUiClean = false; 19420 } 19421 app.trimMemoryLevel = 0; 19422 } 19423 } 19424 19425 if (mAlwaysFinishActivities) { 19426 // Need to do this on its own message because the stack may not 19427 // be in a consistent state at this point. 19428 mStackSupervisor.scheduleDestroyAllActivities(null, "always-finish"); 19429 } 19430 19431 if (allChanged) { 19432 requestPssAllProcsLocked(now, false, mProcessStats.isMemFactorLowered()); 19433 } 19434 19435 // Update from any uid changes. 19436 for (int i=mActiveUids.size()-1; i>=0; i--) { 19437 final UidRecord uidRec = mActiveUids.valueAt(i); 19438 if (uidRec.setProcState != uidRec.curProcState) { 19439 if (DEBUG_UID_OBSERVERS) Slog.i(TAG_UID_OBSERVERS, 19440 "Changes in " + uidRec + ": proc state from " + uidRec.setProcState 19441 + " to " + uidRec.curProcState); 19442 uidRec.setProcState = uidRec.curProcState; 19443 enqueueUidChangeLocked(uidRec, false); 19444 } 19445 } 19446 19447 if (mProcessStats.shouldWriteNowLocked(now)) { 19448 mHandler.post(new Runnable() { 19449 @Override public void run() { 19450 synchronized (ActivityManagerService.this) { 19451 mProcessStats.writeStateAsyncLocked(); 19452 } 19453 } 19454 }); 19455 } 19456 19457 if (DEBUG_OOM_ADJ) { 19458 final long duration = SystemClock.uptimeMillis() - now; 19459 if (false) { 19460 Slog.d(TAG_OOM_ADJ, "Did OOM ADJ in " + duration + "ms", 19461 new RuntimeException("here").fillInStackTrace()); 19462 } else { 19463 Slog.d(TAG_OOM_ADJ, "Did OOM ADJ in " + duration + "ms"); 19464 } 19465 } 19466 } 19467 trimApplications()19468 final void trimApplications() { 19469 synchronized (this) { 19470 int i; 19471 19472 // First remove any unused application processes whose package 19473 // has been removed. 19474 for (i=mRemovedProcesses.size()-1; i>=0; i--) { 19475 final ProcessRecord app = mRemovedProcesses.get(i); 19476 if (app.activities.size() == 0 19477 && app.curReceiver == null && app.services.size() == 0) { 19478 Slog.i( 19479 TAG, "Exiting empty application process " 19480 + app.processName + " (" 19481 + (app.thread != null ? app.thread.asBinder() : null) 19482 + ")\n"); 19483 if (app.pid > 0 && app.pid != MY_PID) { 19484 app.kill("empty", false); 19485 } else { 19486 try { 19487 app.thread.scheduleExit(); 19488 } catch (Exception e) { 19489 // Ignore exceptions. 19490 } 19491 } 19492 cleanUpApplicationRecordLocked(app, false, true, -1); 19493 mRemovedProcesses.remove(i); 19494 19495 if (app.persistent) { 19496 addAppLocked(app.info, false, null /* ABI override */); 19497 } 19498 } 19499 } 19500 19501 // Now update the oom adj for all processes. 19502 updateOomAdjLocked(); 19503 } 19504 } 19505 19506 /** This method sends the specified signal to each of the persistent apps */ signalPersistentProcesses(int sig)19507 public void signalPersistentProcesses(int sig) throws RemoteException { 19508 if (sig != Process.SIGNAL_USR1) { 19509 throw new SecurityException("Only SIGNAL_USR1 is allowed"); 19510 } 19511 19512 synchronized (this) { 19513 if (checkCallingPermission(android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES) 19514 != PackageManager.PERMISSION_GRANTED) { 19515 throw new SecurityException("Requires permission " 19516 + android.Manifest.permission.SIGNAL_PERSISTENT_PROCESSES); 19517 } 19518 19519 for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) { 19520 ProcessRecord r = mLruProcesses.get(i); 19521 if (r.thread != null && r.persistent) { 19522 Process.sendSignal(r.pid, sig); 19523 } 19524 } 19525 } 19526 } 19527 stopProfilerLocked(ProcessRecord proc, int profileType)19528 private void stopProfilerLocked(ProcessRecord proc, int profileType) { 19529 if (proc == null || proc == mProfileProc) { 19530 proc = mProfileProc; 19531 profileType = mProfileType; 19532 clearProfilerLocked(); 19533 } 19534 if (proc == null) { 19535 return; 19536 } 19537 try { 19538 proc.thread.profilerControl(false, null, profileType); 19539 } catch (RemoteException e) { 19540 throw new IllegalStateException("Process disappeared"); 19541 } 19542 } 19543 clearProfilerLocked()19544 private void clearProfilerLocked() { 19545 if (mProfileFd != null) { 19546 try { 19547 mProfileFd.close(); 19548 } catch (IOException e) { 19549 } 19550 } 19551 mProfileApp = null; 19552 mProfileProc = null; 19553 mProfileFile = null; 19554 mProfileType = 0; 19555 mAutoStopProfiler = false; 19556 mSamplingInterval = 0; 19557 } 19558 profileControl(String process, int userId, boolean start, ProfilerInfo profilerInfo, int profileType)19559 public boolean profileControl(String process, int userId, boolean start, 19560 ProfilerInfo profilerInfo, int profileType) throws RemoteException { 19561 19562 try { 19563 synchronized (this) { 19564 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 19565 // its own permission. 19566 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 19567 != PackageManager.PERMISSION_GRANTED) { 19568 throw new SecurityException("Requires permission " 19569 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 19570 } 19571 19572 if (start && (profilerInfo == null || profilerInfo.profileFd == null)) { 19573 throw new IllegalArgumentException("null profile info or fd"); 19574 } 19575 19576 ProcessRecord proc = null; 19577 if (process != null) { 19578 proc = findProcessLocked(process, userId, "profileControl"); 19579 } 19580 19581 if (start && (proc == null || proc.thread == null)) { 19582 throw new IllegalArgumentException("Unknown process: " + process); 19583 } 19584 19585 if (start) { 19586 stopProfilerLocked(null, 0); 19587 setProfileApp(proc.info, proc.processName, profilerInfo); 19588 mProfileProc = proc; 19589 mProfileType = profileType; 19590 ParcelFileDescriptor fd = profilerInfo.profileFd; 19591 try { 19592 fd = fd.dup(); 19593 } catch (IOException e) { 19594 fd = null; 19595 } 19596 profilerInfo.profileFd = fd; 19597 proc.thread.profilerControl(start, profilerInfo, profileType); 19598 fd = null; 19599 mProfileFd = null; 19600 } else { 19601 stopProfilerLocked(proc, profileType); 19602 if (profilerInfo != null && profilerInfo.profileFd != null) { 19603 try { 19604 profilerInfo.profileFd.close(); 19605 } catch (IOException e) { 19606 } 19607 } 19608 } 19609 19610 return true; 19611 } 19612 } catch (RemoteException e) { 19613 throw new IllegalStateException("Process disappeared"); 19614 } finally { 19615 if (profilerInfo != null && profilerInfo.profileFd != null) { 19616 try { 19617 profilerInfo.profileFd.close(); 19618 } catch (IOException e) { 19619 } 19620 } 19621 } 19622 } 19623 findProcessLocked(String process, int userId, String callName)19624 private ProcessRecord findProcessLocked(String process, int userId, String callName) { 19625 userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), 19626 userId, true, ALLOW_FULL_ONLY, callName, null); 19627 ProcessRecord proc = null; 19628 try { 19629 int pid = Integer.parseInt(process); 19630 synchronized (mPidsSelfLocked) { 19631 proc = mPidsSelfLocked.get(pid); 19632 } 19633 } catch (NumberFormatException e) { 19634 } 19635 19636 if (proc == null) { 19637 ArrayMap<String, SparseArray<ProcessRecord>> all 19638 = mProcessNames.getMap(); 19639 SparseArray<ProcessRecord> procs = all.get(process); 19640 if (procs != null && procs.size() > 0) { 19641 proc = procs.valueAt(0); 19642 if (userId != UserHandle.USER_ALL && proc.userId != userId) { 19643 for (int i=1; i<procs.size(); i++) { 19644 ProcessRecord thisProc = procs.valueAt(i); 19645 if (thisProc.userId == userId) { 19646 proc = thisProc; 19647 break; 19648 } 19649 } 19650 } 19651 } 19652 } 19653 19654 return proc; 19655 } 19656 dumpHeap(String process, int userId, boolean managed, String path, ParcelFileDescriptor fd)19657 public boolean dumpHeap(String process, int userId, boolean managed, 19658 String path, ParcelFileDescriptor fd) throws RemoteException { 19659 19660 try { 19661 synchronized (this) { 19662 // note: hijacking SET_ACTIVITY_WATCHER, but should be changed to 19663 // its own permission (same as profileControl). 19664 if (checkCallingPermission(android.Manifest.permission.SET_ACTIVITY_WATCHER) 19665 != PackageManager.PERMISSION_GRANTED) { 19666 throw new SecurityException("Requires permission " 19667 + android.Manifest.permission.SET_ACTIVITY_WATCHER); 19668 } 19669 19670 if (fd == null) { 19671 throw new IllegalArgumentException("null fd"); 19672 } 19673 19674 ProcessRecord proc = findProcessLocked(process, userId, "dumpHeap"); 19675 if (proc == null || proc.thread == null) { 19676 throw new IllegalArgumentException("Unknown process: " + process); 19677 } 19678 19679 boolean isDebuggable = "1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0")); 19680 if (!isDebuggable) { 19681 if ((proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 19682 throw new SecurityException("Process not debuggable: " + proc); 19683 } 19684 } 19685 19686 proc.thread.dumpHeap(managed, path, fd); 19687 fd = null; 19688 return true; 19689 } 19690 } catch (RemoteException e) { 19691 throw new IllegalStateException("Process disappeared"); 19692 } finally { 19693 if (fd != null) { 19694 try { 19695 fd.close(); 19696 } catch (IOException e) { 19697 } 19698 } 19699 } 19700 } 19701 19702 @Override setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, String reportPackage)19703 public void setDumpHeapDebugLimit(String processName, int uid, long maxMemSize, 19704 String reportPackage) { 19705 if (processName != null) { 19706 enforceCallingPermission(android.Manifest.permission.SET_DEBUG_APP, 19707 "setDumpHeapDebugLimit()"); 19708 } else { 19709 synchronized (mPidsSelfLocked) { 19710 ProcessRecord proc = mPidsSelfLocked.get(Binder.getCallingPid()); 19711 if (proc == null) { 19712 throw new SecurityException("No process found for calling pid " 19713 + Binder.getCallingPid()); 19714 } 19715 if (!Build.IS_DEBUGGABLE 19716 && (proc.info.flags&ApplicationInfo.FLAG_DEBUGGABLE) == 0) { 19717 throw new SecurityException("Not running a debuggable build"); 19718 } 19719 processName = proc.processName; 19720 uid = proc.uid; 19721 if (reportPackage != null && !proc.pkgList.containsKey(reportPackage)) { 19722 throw new SecurityException("Package " + reportPackage + " is not running in " 19723 + proc); 19724 } 19725 } 19726 } 19727 synchronized (this) { 19728 if (maxMemSize > 0) { 19729 mMemWatchProcesses.put(processName, uid, new Pair(maxMemSize, reportPackage)); 19730 } else { 19731 if (uid != 0) { 19732 mMemWatchProcesses.remove(processName, uid); 19733 } else { 19734 mMemWatchProcesses.getMap().remove(processName); 19735 } 19736 } 19737 } 19738 } 19739 19740 @Override dumpHeapFinished(String path)19741 public void dumpHeapFinished(String path) { 19742 synchronized (this) { 19743 if (Binder.getCallingPid() != mMemWatchDumpPid) { 19744 Slog.w(TAG, "dumpHeapFinished: Calling pid " + Binder.getCallingPid() 19745 + " does not match last pid " + mMemWatchDumpPid); 19746 return; 19747 } 19748 if (mMemWatchDumpFile == null || !mMemWatchDumpFile.equals(path)) { 19749 Slog.w(TAG, "dumpHeapFinished: Calling path " + path 19750 + " does not match last path " + mMemWatchDumpFile); 19751 return; 19752 } 19753 if (DEBUG_PSS) Slog.d(TAG_PSS, "Dump heap finished for " + path); 19754 mHandler.sendEmptyMessage(POST_DUMP_HEAP_NOTIFICATION_MSG); 19755 } 19756 } 19757 19758 /** In this method we try to acquire our lock to make sure that we have not deadlocked */ monitor()19759 public void monitor() { 19760 synchronized (this) { } 19761 } 19762 onCoreSettingsChange(Bundle settings)19763 void onCoreSettingsChange(Bundle settings) { 19764 for (int i = mLruProcesses.size() - 1; i >= 0; i--) { 19765 ProcessRecord processRecord = mLruProcesses.get(i); 19766 try { 19767 if (processRecord.thread != null) { 19768 processRecord.thread.setCoreSettings(settings); 19769 } 19770 } catch (RemoteException re) { 19771 /* ignore */ 19772 } 19773 } 19774 } 19775 19776 // Multi-user methods 19777 19778 /** 19779 * Start user, if its not already running, but don't bring it to foreground. 19780 */ 19781 @Override startUserInBackground(final int userId)19782 public boolean startUserInBackground(final int userId) { 19783 return startUser(userId, /* foreground */ false); 19784 } 19785 19786 /** 19787 * Start user, if its not already running, and bring it to foreground. 19788 */ startUserInForeground(final int userId, Dialog dlg)19789 boolean startUserInForeground(final int userId, Dialog dlg) { 19790 boolean result = startUser(userId, /* foreground */ true); 19791 dlg.dismiss(); 19792 return result; 19793 } 19794 19795 /** 19796 * Refreshes the list of users related to the current user when either a 19797 * user switch happens or when a new related user is started in the 19798 * background. 19799 */ updateCurrentProfileIdsLocked()19800 private void updateCurrentProfileIdsLocked() { 19801 final List<UserInfo> profiles = getUserManagerLocked().getProfiles( 19802 mCurrentUserId, false /* enabledOnly */); 19803 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null 19804 for (int i = 0; i < currentProfileIds.length; i++) { 19805 currentProfileIds[i] = profiles.get(i).id; 19806 } 19807 mCurrentProfileIds = currentProfileIds; 19808 19809 synchronized (mUserProfileGroupIdsSelfLocked) { 19810 mUserProfileGroupIdsSelfLocked.clear(); 19811 final List<UserInfo> users = getUserManagerLocked().getUsers(false); 19812 for (int i = 0; i < users.size(); i++) { 19813 UserInfo user = users.get(i); 19814 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) { 19815 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId); 19816 } 19817 } 19818 } 19819 } 19820 getProfileIdsLocked(int userId)19821 private Set<Integer> getProfileIdsLocked(int userId) { 19822 Set<Integer> userIds = new HashSet<Integer>(); 19823 final List<UserInfo> profiles = getUserManagerLocked().getProfiles( 19824 userId, false /* enabledOnly */); 19825 for (UserInfo user : profiles) { 19826 userIds.add(Integer.valueOf(user.id)); 19827 } 19828 return userIds; 19829 } 19830 19831 @Override switchUser(final int userId)19832 public boolean switchUser(final int userId) { 19833 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId); 19834 String userName; 19835 synchronized (this) { 19836 UserInfo userInfo = getUserManagerLocked().getUserInfo(userId); 19837 if (userInfo == null) { 19838 Slog.w(TAG, "No user info for user #" + userId); 19839 return false; 19840 } 19841 if (userInfo.isManagedProfile()) { 19842 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user"); 19843 return false; 19844 } 19845 userName = userInfo.name; 19846 mTargetUserId = userId; 19847 } 19848 mUiHandler.removeMessages(START_USER_SWITCH_MSG); 19849 mUiHandler.sendMessage(mUiHandler.obtainMessage(START_USER_SWITCH_MSG, userId, 0, userName)); 19850 return true; 19851 } 19852 showUserSwitchDialog(int userId, String userName)19853 private void showUserSwitchDialog(int userId, String userName) { 19854 // The dialog will show and then initiate the user switch by calling startUserInForeground 19855 Dialog d = new UserSwitchingDialog(this, mContext, userId, userName, 19856 true /* above system */); 19857 d.show(); 19858 } 19859 startUser(final int userId, final boolean foreground)19860 private boolean startUser(final int userId, final boolean foreground) { 19861 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 19862 != PackageManager.PERMISSION_GRANTED) { 19863 String msg = "Permission Denial: switchUser() from pid=" 19864 + Binder.getCallingPid() 19865 + ", uid=" + Binder.getCallingUid() 19866 + " requires " + INTERACT_ACROSS_USERS_FULL; 19867 Slog.w(TAG, msg); 19868 throw new SecurityException(msg); 19869 } 19870 19871 if (DEBUG_MU) Slog.i(TAG_MU, "starting userid:" + userId + " fore:" + foreground); 19872 19873 final long ident = Binder.clearCallingIdentity(); 19874 try { 19875 synchronized (this) { 19876 final int oldUserId = mCurrentUserId; 19877 if (oldUserId == userId) { 19878 return true; 19879 } 19880 19881 mStackSupervisor.setLockTaskModeLocked(null, ActivityManager.LOCK_TASK_MODE_NONE, 19882 "startUser", false); 19883 19884 final UserInfo userInfo = getUserManagerLocked().getUserInfo(userId); 19885 if (userInfo == null) { 19886 Slog.w(TAG, "No user info for user #" + userId); 19887 return false; 19888 } 19889 if (foreground && userInfo.isManagedProfile()) { 19890 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user"); 19891 return false; 19892 } 19893 19894 if (foreground) { 19895 mWindowManager.startFreezingScreen(R.anim.screen_user_exit, 19896 R.anim.screen_user_enter); 19897 } 19898 19899 boolean needStart = false; 19900 19901 // If the user we are switching to is not currently started, then 19902 // we need to start it now. 19903 if (mStartedUsers.get(userId) == null) { 19904 mStartedUsers.put(userId, new UserState(new UserHandle(userId), false)); 19905 updateStartedUserArrayLocked(); 19906 needStart = true; 19907 } 19908 19909 final Integer userIdInt = Integer.valueOf(userId); 19910 mUserLru.remove(userIdInt); 19911 mUserLru.add(userIdInt); 19912 19913 if (foreground) { 19914 mCurrentUserId = userId; 19915 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up 19916 updateCurrentProfileIdsLocked(); 19917 mWindowManager.setCurrentUser(userId, mCurrentProfileIds); 19918 // Once the internal notion of the active user has switched, we lock the device 19919 // with the option to show the user switcher on the keyguard. 19920 mWindowManager.lockNow(null); 19921 } else { 19922 final Integer currentUserIdInt = Integer.valueOf(mCurrentUserId); 19923 updateCurrentProfileIdsLocked(); 19924 mWindowManager.setCurrentProfileIds(mCurrentProfileIds); 19925 mUserLru.remove(currentUserIdInt); 19926 mUserLru.add(currentUserIdInt); 19927 } 19928 19929 final UserState uss = mStartedUsers.get(userId); 19930 19931 // Make sure user is in the started state. If it is currently 19932 // stopping, we need to knock that off. 19933 if (uss.mState == UserState.STATE_STOPPING) { 19934 // If we are stopping, we haven't sent ACTION_SHUTDOWN, 19935 // so we can just fairly silently bring the user back from 19936 // the almost-dead. 19937 uss.mState = UserState.STATE_RUNNING; 19938 updateStartedUserArrayLocked(); 19939 needStart = true; 19940 } else if (uss.mState == UserState.STATE_SHUTDOWN) { 19941 // This means ACTION_SHUTDOWN has been sent, so we will 19942 // need to treat this as a new boot of the user. 19943 uss.mState = UserState.STATE_BOOTING; 19944 updateStartedUserArrayLocked(); 19945 needStart = true; 19946 } 19947 19948 if (uss.mState == UserState.STATE_BOOTING) { 19949 // Booting up a new user, need to tell system services about it. 19950 // Note that this is on the same handler as scheduling of broadcasts, 19951 // which is important because it needs to go first. 19952 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0)); 19953 } 19954 19955 if (foreground) { 19956 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId, 19957 oldUserId)); 19958 mHandler.removeMessages(REPORT_USER_SWITCH_MSG); 19959 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 19960 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG, 19961 oldUserId, userId, uss)); 19962 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG, 19963 oldUserId, userId, uss), USER_SWITCH_TIMEOUT); 19964 } 19965 19966 if (needStart) { 19967 // Send USER_STARTED broadcast 19968 Intent intent = new Intent(Intent.ACTION_USER_STARTED); 19969 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 19970 | Intent.FLAG_RECEIVER_FOREGROUND); 19971 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19972 broadcastIntentLocked(null, null, intent, 19973 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 19974 null, false, false, MY_PID, Process.SYSTEM_UID, userId); 19975 } 19976 19977 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) { 19978 if (userId != UserHandle.USER_OWNER) { 19979 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE); 19980 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 19981 broadcastIntentLocked(null, null, intent, null, 19982 new IIntentReceiver.Stub() { 19983 public void performReceive(Intent intent, int resultCode, 19984 String data, Bundle extras, boolean ordered, 19985 boolean sticky, int sendingUser) { 19986 onUserInitialized(uss, foreground, oldUserId, userId); 19987 } 19988 }, 0, null, null, null, AppOpsManager.OP_NONE, 19989 null, true, false, MY_PID, Process.SYSTEM_UID, userId); 19990 uss.initializing = true; 19991 } else { 19992 getUserManagerLocked().makeInitialized(userInfo.id); 19993 } 19994 } 19995 19996 if (foreground) { 19997 if (!uss.initializing) { 19998 moveUserToForeground(uss, oldUserId, userId); 19999 } 20000 } else { 20001 mStackSupervisor.startBackgroundUserLocked(userId, uss); 20002 } 20003 20004 if (needStart) { 20005 Intent intent = new Intent(Intent.ACTION_USER_STARTING); 20006 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 20007 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 20008 broadcastIntentLocked(null, null, intent, 20009 null, new IIntentReceiver.Stub() { 20010 @Override 20011 public void performReceive(Intent intent, int resultCode, 20012 String data, Bundle extras, boolean ordered, boolean sticky, 20013 int sendingUser) throws RemoteException { 20014 } 20015 }, 0, null, null, 20016 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, 20017 null, true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 20018 } 20019 } 20020 } finally { 20021 Binder.restoreCallingIdentity(ident); 20022 } 20023 20024 return true; 20025 } 20026 dispatchForegroundProfileChanged(int userId)20027 void dispatchForegroundProfileChanged(int userId) { 20028 final int N = mUserSwitchObservers.beginBroadcast(); 20029 for (int i = 0; i < N; i++) { 20030 try { 20031 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId); 20032 } catch (RemoteException e) { 20033 // Ignore 20034 } 20035 } 20036 mUserSwitchObservers.finishBroadcast(); 20037 } 20038 sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId)20039 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) { 20040 long ident = Binder.clearCallingIdentity(); 20041 try { 20042 Intent intent; 20043 if (oldUserId >= 0) { 20044 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user 20045 List<UserInfo> profiles = mUserManager.getProfiles(oldUserId, false); 20046 int count = profiles.size(); 20047 for (int i = 0; i < count; i++) { 20048 int profileUserId = profiles.get(i).id; 20049 intent = new Intent(Intent.ACTION_USER_BACKGROUND); 20050 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 20051 | Intent.FLAG_RECEIVER_FOREGROUND); 20052 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 20053 broadcastIntentLocked(null, null, intent, 20054 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 20055 null, false, false, MY_PID, Process.SYSTEM_UID, profileUserId); 20056 } 20057 } 20058 if (newUserId >= 0) { 20059 // Send USER_FOREGROUND broadcast to all profiles of the incoming user 20060 List<UserInfo> profiles = mUserManager.getProfiles(newUserId, false); 20061 int count = profiles.size(); 20062 for (int i = 0; i < count; i++) { 20063 int profileUserId = profiles.get(i).id; 20064 intent = new Intent(Intent.ACTION_USER_FOREGROUND); 20065 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 20066 | Intent.FLAG_RECEIVER_FOREGROUND); 20067 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId); 20068 broadcastIntentLocked(null, null, intent, 20069 null, null, 0, null, null, null, AppOpsManager.OP_NONE, 20070 null, false, false, MY_PID, Process.SYSTEM_UID, profileUserId); 20071 } 20072 intent = new Intent(Intent.ACTION_USER_SWITCHED); 20073 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY 20074 | Intent.FLAG_RECEIVER_FOREGROUND); 20075 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId); 20076 broadcastIntentLocked(null, null, intent, 20077 null, null, 0, null, null, 20078 new String[] {android.Manifest.permission.MANAGE_USERS}, 20079 AppOpsManager.OP_NONE, null, false, false, MY_PID, Process.SYSTEM_UID, 20080 UserHandle.USER_ALL); 20081 } 20082 } finally { 20083 Binder.restoreCallingIdentity(ident); 20084 } 20085 } 20086 dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId)20087 void dispatchUserSwitch(final UserState uss, final int oldUserId, 20088 final int newUserId) { 20089 final int N = mUserSwitchObservers.beginBroadcast(); 20090 if (N > 0) { 20091 final IRemoteCallback callback = new IRemoteCallback.Stub() { 20092 int mCount = 0; 20093 @Override 20094 public void sendResult(Bundle data) throws RemoteException { 20095 synchronized (ActivityManagerService.this) { 20096 if (mCurUserSwitchCallback == this) { 20097 mCount++; 20098 if (mCount == N) { 20099 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 20100 } 20101 } 20102 } 20103 } 20104 }; 20105 synchronized (this) { 20106 uss.switching = true; 20107 mCurUserSwitchCallback = callback; 20108 } 20109 for (int i=0; i<N; i++) { 20110 try { 20111 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching( 20112 newUserId, callback); 20113 } catch (RemoteException e) { 20114 } 20115 } 20116 } else { 20117 synchronized (this) { 20118 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 20119 } 20120 } 20121 mUserSwitchObservers.finishBroadcast(); 20122 } 20123 timeoutUserSwitch(UserState uss, int oldUserId, int newUserId)20124 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) { 20125 synchronized (this) { 20126 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId); 20127 sendContinueUserSwitchLocked(uss, oldUserId, newUserId); 20128 } 20129 } 20130 sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId)20131 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) { 20132 mCurUserSwitchCallback = null; 20133 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG); 20134 mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG, 20135 oldUserId, newUserId, uss)); 20136 } 20137 onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId)20138 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) { 20139 synchronized (this) { 20140 if (foreground) { 20141 moveUserToForeground(uss, oldUserId, newUserId); 20142 } 20143 } 20144 20145 completeSwitchAndInitialize(uss, newUserId, true, false); 20146 } 20147 moveUserToForeground(UserState uss, int oldUserId, int newUserId)20148 void moveUserToForeground(UserState uss, int oldUserId, int newUserId) { 20149 boolean homeInFront = mStackSupervisor.switchUserLocked(newUserId, uss); 20150 if (homeInFront) { 20151 startHomeActivityLocked(newUserId, "moveUserToFroreground"); 20152 } else { 20153 mStackSupervisor.resumeTopActivitiesLocked(); 20154 } 20155 EventLogTags.writeAmSwitchUser(newUserId); 20156 getUserManagerLocked().onUserForeground(newUserId); 20157 sendUserSwitchBroadcastsLocked(oldUserId, newUserId); 20158 } 20159 continueUserSwitch(UserState uss, int oldUserId, int newUserId)20160 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) { 20161 completeSwitchAndInitialize(uss, newUserId, false, true); 20162 } 20163 completeSwitchAndInitialize(UserState uss, int newUserId, boolean clearInitializing, boolean clearSwitching)20164 void completeSwitchAndInitialize(UserState uss, int newUserId, 20165 boolean clearInitializing, boolean clearSwitching) { 20166 boolean unfrozen = false; 20167 synchronized (this) { 20168 if (clearInitializing) { 20169 uss.initializing = false; 20170 getUserManagerLocked().makeInitialized(uss.mHandle.getIdentifier()); 20171 } 20172 if (clearSwitching) { 20173 uss.switching = false; 20174 } 20175 if (!uss.switching && !uss.initializing) { 20176 mWindowManager.stopFreezingScreen(); 20177 unfrozen = true; 20178 } 20179 } 20180 if (unfrozen) { 20181 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG); 20182 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG, 20183 newUserId, 0)); 20184 } 20185 stopGuestUserIfBackground(); 20186 } 20187 20188 /** Called on handler thread */ dispatchUserSwitchComplete(int userId)20189 void dispatchUserSwitchComplete(int userId) { 20190 final int observerCount = mUserSwitchObservers.beginBroadcast(); 20191 for (int i = 0; i < observerCount; i++) { 20192 try { 20193 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId); 20194 } catch (RemoteException e) { 20195 } 20196 } 20197 mUserSwitchObservers.finishBroadcast(); 20198 } 20199 20200 /** 20201 * Stops the guest user if it has gone to the background. 20202 */ stopGuestUserIfBackground()20203 private void stopGuestUserIfBackground() { 20204 synchronized (this) { 20205 final int num = mUserLru.size(); 20206 for (int i = 0; i < num; i++) { 20207 Integer oldUserId = mUserLru.get(i); 20208 UserState oldUss = mStartedUsers.get(oldUserId); 20209 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId 20210 || oldUss.mState == UserState.STATE_STOPPING 20211 || oldUss.mState == UserState.STATE_SHUTDOWN) { 20212 continue; 20213 } 20214 UserInfo userInfo = mUserManager.getUserInfo(oldUserId); 20215 if (userInfo.isGuest()) { 20216 // This is a user to be stopped. 20217 stopUserLocked(oldUserId, null); 20218 break; 20219 } 20220 } 20221 } 20222 } 20223 scheduleStartProfilesLocked()20224 void scheduleStartProfilesLocked() { 20225 if (!mHandler.hasMessages(START_PROFILES_MSG)) { 20226 mHandler.sendMessageDelayed(mHandler.obtainMessage(START_PROFILES_MSG), 20227 DateUtils.SECOND_IN_MILLIS); 20228 } 20229 } 20230 startProfilesLocked()20231 void startProfilesLocked() { 20232 if (DEBUG_MU) Slog.i(TAG_MU, "startProfilesLocked"); 20233 List<UserInfo> profiles = getUserManagerLocked().getProfiles( 20234 mCurrentUserId, false /* enabledOnly */); 20235 List<UserInfo> toStart = new ArrayList<UserInfo>(profiles.size()); 20236 for (UserInfo user : profiles) { 20237 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED 20238 && user.id != mCurrentUserId) { 20239 toStart.add(user); 20240 } 20241 } 20242 final int n = toStart.size(); 20243 int i = 0; 20244 for (; i < n && i < (MAX_RUNNING_USERS - 1); ++i) { 20245 startUserInBackground(toStart.get(i).id); 20246 } 20247 if (i < n) { 20248 Slog.w(TAG_MU, "More profiles than MAX_RUNNING_USERS"); 20249 } 20250 } 20251 finishUserBoot(UserState uss)20252 void finishUserBoot(UserState uss) { 20253 synchronized (this) { 20254 if (uss.mState == UserState.STATE_BOOTING 20255 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) { 20256 uss.mState = UserState.STATE_RUNNING; 20257 final int userId = uss.mHandle.getIdentifier(); 20258 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null); 20259 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 20260 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT); 20261 broadcastIntentLocked(null, null, intent, 20262 null, null, 0, null, null, 20263 new String[] {android.Manifest.permission.RECEIVE_BOOT_COMPLETED}, 20264 AppOpsManager.OP_NONE, null, true, false, MY_PID, Process.SYSTEM_UID, 20265 userId); 20266 } 20267 } 20268 } 20269 finishUserSwitch(UserState uss)20270 void finishUserSwitch(UserState uss) { 20271 synchronized (this) { 20272 finishUserBoot(uss); 20273 20274 startProfilesLocked(); 20275 20276 int num = mUserLru.size(); 20277 int i = 0; 20278 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) { 20279 Integer oldUserId = mUserLru.get(i); 20280 UserState oldUss = mStartedUsers.get(oldUserId); 20281 if (oldUss == null) { 20282 // Shouldn't happen, but be sane if it does. 20283 mUserLru.remove(i); 20284 num--; 20285 continue; 20286 } 20287 if (oldUss.mState == UserState.STATE_STOPPING 20288 || oldUss.mState == UserState.STATE_SHUTDOWN) { 20289 // This user is already stopping, doesn't count. 20290 num--; 20291 i++; 20292 continue; 20293 } 20294 if (oldUserId == UserHandle.USER_OWNER || oldUserId == mCurrentUserId) { 20295 // Owner and current can't be stopped, but count as running. 20296 i++; 20297 continue; 20298 } 20299 // This is a user to be stopped. 20300 stopUserLocked(oldUserId, null); 20301 num--; 20302 i++; 20303 } 20304 } 20305 } 20306 20307 @Override stopUser(final int userId, final IStopUserCallback callback)20308 public int stopUser(final int userId, final IStopUserCallback callback) { 20309 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 20310 != PackageManager.PERMISSION_GRANTED) { 20311 String msg = "Permission Denial: switchUser() from pid=" 20312 + Binder.getCallingPid() 20313 + ", uid=" + Binder.getCallingUid() 20314 + " requires " + INTERACT_ACROSS_USERS_FULL; 20315 Slog.w(TAG, msg); 20316 throw new SecurityException(msg); 20317 } 20318 if (userId < 0 || userId == UserHandle.USER_OWNER) { 20319 throw new IllegalArgumentException("Can't stop primary user " + userId); 20320 } 20321 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId); 20322 synchronized (this) { 20323 return stopUserLocked(userId, callback); 20324 } 20325 } 20326 stopUserLocked(final int userId, final IStopUserCallback callback)20327 private int stopUserLocked(final int userId, final IStopUserCallback callback) { 20328 if (DEBUG_MU) Slog.i(TAG_MU, "stopUserLocked userId=" + userId); 20329 if (mCurrentUserId == userId && mTargetUserId == UserHandle.USER_NULL) { 20330 return ActivityManager.USER_OP_IS_CURRENT; 20331 } 20332 20333 final UserState uss = mStartedUsers.get(userId); 20334 if (uss == null) { 20335 // User is not started, nothing to do... but we do need to 20336 // callback if requested. 20337 if (callback != null) { 20338 mHandler.post(new Runnable() { 20339 @Override 20340 public void run() { 20341 try { 20342 callback.userStopped(userId); 20343 } catch (RemoteException e) { 20344 } 20345 } 20346 }); 20347 } 20348 return ActivityManager.USER_OP_SUCCESS; 20349 } 20350 20351 if (callback != null) { 20352 uss.mStopCallbacks.add(callback); 20353 } 20354 20355 if (uss.mState != UserState.STATE_STOPPING 20356 && uss.mState != UserState.STATE_SHUTDOWN) { 20357 uss.mState = UserState.STATE_STOPPING; 20358 updateStartedUserArrayLocked(); 20359 20360 long ident = Binder.clearCallingIdentity(); 20361 try { 20362 // We are going to broadcast ACTION_USER_STOPPING and then 20363 // once that is done send a final ACTION_SHUTDOWN and then 20364 // stop the user. 20365 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING); 20366 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY); 20367 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 20368 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true); 20369 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN); 20370 // This is the result receiver for the final shutdown broadcast. 20371 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() { 20372 @Override 20373 public void performReceive(Intent intent, int resultCode, String data, 20374 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 20375 finishUserStop(uss); 20376 } 20377 }; 20378 // This is the result receiver for the initial stopping broadcast. 20379 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() { 20380 @Override 20381 public void performReceive(Intent intent, int resultCode, String data, 20382 Bundle extras, boolean ordered, boolean sticky, int sendingUser) { 20383 // On to the next. 20384 synchronized (ActivityManagerService.this) { 20385 if (uss.mState != UserState.STATE_STOPPING) { 20386 // Whoops, we are being started back up. Abort, abort! 20387 return; 20388 } 20389 uss.mState = UserState.STATE_SHUTDOWN; 20390 } 20391 mBatteryStatsService.noteEvent( 20392 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH, 20393 Integer.toString(userId), userId); 20394 mSystemServiceManager.stopUser(userId); 20395 broadcastIntentLocked(null, null, shutdownIntent, 20396 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE, 20397 null, true, false, MY_PID, Process.SYSTEM_UID, userId); 20398 } 20399 }; 20400 // Kick things off. 20401 broadcastIntentLocked(null, null, stoppingIntent, 20402 null, stoppingReceiver, 0, null, null, 20403 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, 20404 null, true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL); 20405 } finally { 20406 Binder.restoreCallingIdentity(ident); 20407 } 20408 } 20409 20410 return ActivityManager.USER_OP_SUCCESS; 20411 } 20412 finishUserStop(UserState uss)20413 void finishUserStop(UserState uss) { 20414 final int userId = uss.mHandle.getIdentifier(); 20415 boolean stopped; 20416 ArrayList<IStopUserCallback> callbacks; 20417 synchronized (this) { 20418 callbacks = new ArrayList<IStopUserCallback>(uss.mStopCallbacks); 20419 if (mStartedUsers.get(userId) != uss) { 20420 stopped = false; 20421 } else if (uss.mState != UserState.STATE_SHUTDOWN) { 20422 stopped = false; 20423 } else { 20424 stopped = true; 20425 // User can no longer run. 20426 mStartedUsers.remove(userId); 20427 mUserLru.remove(Integer.valueOf(userId)); 20428 updateStartedUserArrayLocked(); 20429 20430 // Clean up all state and processes associated with the user. 20431 // Kill all the processes for the user. 20432 forceStopUserLocked(userId, "finish user"); 20433 } 20434 20435 // Explicitly remove the old information in mRecentTasks. 20436 mRecentTasks.removeTasksForUserLocked(userId); 20437 } 20438 20439 for (int i=0; i<callbacks.size(); i++) { 20440 try { 20441 if (stopped) callbacks.get(i).userStopped(userId); 20442 else callbacks.get(i).userStopAborted(userId); 20443 } catch (RemoteException e) { 20444 } 20445 } 20446 20447 if (stopped) { 20448 mSystemServiceManager.cleanupUser(userId); 20449 synchronized (this) { 20450 mStackSupervisor.removeUserLocked(userId); 20451 } 20452 } 20453 } 20454 20455 @Override getCurrentUser()20456 public UserInfo getCurrentUser() { 20457 if ((checkCallingPermission(INTERACT_ACROSS_USERS) 20458 != PackageManager.PERMISSION_GRANTED) && ( 20459 checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 20460 != PackageManager.PERMISSION_GRANTED)) { 20461 String msg = "Permission Denial: getCurrentUser() from pid=" 20462 + Binder.getCallingPid() 20463 + ", uid=" + Binder.getCallingUid() 20464 + " requires " + INTERACT_ACROSS_USERS; 20465 Slog.w(TAG, msg); 20466 throw new SecurityException(msg); 20467 } 20468 synchronized (this) { 20469 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId; 20470 return getUserManagerLocked().getUserInfo(userId); 20471 } 20472 } 20473 getCurrentUserIdLocked()20474 int getCurrentUserIdLocked() { 20475 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId; 20476 } 20477 20478 @Override isUserRunning(int userId, boolean orStopped)20479 public boolean isUserRunning(int userId, boolean orStopped) { 20480 if (checkCallingPermission(INTERACT_ACROSS_USERS) 20481 != PackageManager.PERMISSION_GRANTED) { 20482 String msg = "Permission Denial: isUserRunning() from pid=" 20483 + Binder.getCallingPid() 20484 + ", uid=" + Binder.getCallingUid() 20485 + " requires " + INTERACT_ACROSS_USERS; 20486 Slog.w(TAG, msg); 20487 throw new SecurityException(msg); 20488 } 20489 synchronized (this) { 20490 return isUserRunningLocked(userId, orStopped); 20491 } 20492 } 20493 isUserRunningLocked(int userId, boolean orStopped)20494 boolean isUserRunningLocked(int userId, boolean orStopped) { 20495 UserState state = mStartedUsers.get(userId); 20496 if (state == null) { 20497 return false; 20498 } 20499 if (orStopped) { 20500 return true; 20501 } 20502 return state.mState != UserState.STATE_STOPPING 20503 && state.mState != UserState.STATE_SHUTDOWN; 20504 } 20505 20506 @Override getRunningUserIds()20507 public int[] getRunningUserIds() { 20508 if (checkCallingPermission(INTERACT_ACROSS_USERS) 20509 != PackageManager.PERMISSION_GRANTED) { 20510 String msg = "Permission Denial: isUserRunning() from pid=" 20511 + Binder.getCallingPid() 20512 + ", uid=" + Binder.getCallingUid() 20513 + " requires " + INTERACT_ACROSS_USERS; 20514 Slog.w(TAG, msg); 20515 throw new SecurityException(msg); 20516 } 20517 synchronized (this) { 20518 return mStartedUserArray; 20519 } 20520 } 20521 updateStartedUserArrayLocked()20522 private void updateStartedUserArrayLocked() { 20523 int num = 0; 20524 for (int i=0; i<mStartedUsers.size(); i++) { 20525 UserState uss = mStartedUsers.valueAt(i); 20526 // This list does not include stopping users. 20527 if (uss.mState != UserState.STATE_STOPPING 20528 && uss.mState != UserState.STATE_SHUTDOWN) { 20529 num++; 20530 } 20531 } 20532 mStartedUserArray = new int[num]; 20533 num = 0; 20534 for (int i=0; i<mStartedUsers.size(); i++) { 20535 UserState uss = mStartedUsers.valueAt(i); 20536 if (uss.mState != UserState.STATE_STOPPING 20537 && uss.mState != UserState.STATE_SHUTDOWN) { 20538 mStartedUserArray[num] = mStartedUsers.keyAt(i); 20539 num++; 20540 } 20541 } 20542 } 20543 20544 @Override registerUserSwitchObserver(IUserSwitchObserver observer)20545 public void registerUserSwitchObserver(IUserSwitchObserver observer) { 20546 if (checkCallingPermission(INTERACT_ACROSS_USERS_FULL) 20547 != PackageManager.PERMISSION_GRANTED) { 20548 String msg = "Permission Denial: registerUserSwitchObserver() from pid=" 20549 + Binder.getCallingPid() 20550 + ", uid=" + Binder.getCallingUid() 20551 + " requires " + INTERACT_ACROSS_USERS_FULL; 20552 Slog.w(TAG, msg); 20553 throw new SecurityException(msg); 20554 } 20555 20556 mUserSwitchObservers.register(observer); 20557 } 20558 20559 @Override unregisterUserSwitchObserver(IUserSwitchObserver observer)20560 public void unregisterUserSwitchObserver(IUserSwitchObserver observer) { 20561 mUserSwitchObservers.unregister(observer); 20562 } 20563 getUsersLocked()20564 int[] getUsersLocked() { 20565 UserManagerService ums = getUserManagerLocked(); 20566 return ums != null ? ums.getUserIds() : new int[] { 0 }; 20567 } 20568 getUserManagerLocked()20569 UserManagerService getUserManagerLocked() { 20570 if (mUserManager == null) { 20571 IBinder b = ServiceManager.getService(Context.USER_SERVICE); 20572 mUserManager = (UserManagerService)IUserManager.Stub.asInterface(b); 20573 } 20574 return mUserManager; 20575 } 20576 applyUserId(int uid, int userId)20577 private int applyUserId(int uid, int userId) { 20578 return UserHandle.getUid(userId, uid); 20579 } 20580 getAppInfoForUser(ApplicationInfo info, int userId)20581 ApplicationInfo getAppInfoForUser(ApplicationInfo info, int userId) { 20582 if (info == null) return null; 20583 ApplicationInfo newInfo = new ApplicationInfo(info); 20584 newInfo.uid = applyUserId(info.uid, userId); 20585 newInfo.dataDir = Environment 20586 .getDataUserPackageDirectory(info.volumeUuid, userId, info.packageName) 20587 .getAbsolutePath(); 20588 return newInfo; 20589 } 20590 getActivityInfoForUser(ActivityInfo aInfo, int userId)20591 ActivityInfo getActivityInfoForUser(ActivityInfo aInfo, int userId) { 20592 if (aInfo == null 20593 || (userId < 1 && aInfo.applicationInfo.uid < UserHandle.PER_USER_RANGE)) { 20594 return aInfo; 20595 } 20596 20597 ActivityInfo info = new ActivityInfo(aInfo); 20598 info.applicationInfo = getAppInfoForUser(info.applicationInfo, userId); 20599 return info; 20600 } 20601 20602 private final class LocalService extends ActivityManagerInternal { 20603 @Override onWakefulnessChanged(int wakefulness)20604 public void onWakefulnessChanged(int wakefulness) { 20605 ActivityManagerService.this.onWakefulnessChanged(wakefulness); 20606 } 20607 20608 @Override startIsolatedProcess(String entryPoint, String[] entryPointArgs, String processName, String abiOverride, int uid, Runnable crashHandler)20609 public int startIsolatedProcess(String entryPoint, String[] entryPointArgs, 20610 String processName, String abiOverride, int uid, Runnable crashHandler) { 20611 return ActivityManagerService.this.startIsolatedProcess(entryPoint, entryPointArgs, 20612 processName, abiOverride, uid, crashHandler); 20613 } 20614 20615 @Override acquireSleepToken(String tag)20616 public SleepToken acquireSleepToken(String tag) { 20617 Preconditions.checkNotNull(tag); 20618 20619 synchronized (ActivityManagerService.this) { 20620 SleepTokenImpl token = new SleepTokenImpl(tag); 20621 mSleepTokens.add(token); 20622 updateSleepIfNeededLocked(); 20623 return token; 20624 } 20625 } 20626 20627 @Override getHomeActivityForUser(int userId)20628 public ComponentName getHomeActivityForUser(int userId) { 20629 synchronized (ActivityManagerService.this) { 20630 ActivityRecord homeActivity = mStackSupervisor.getHomeActivityForUser(userId); 20631 return homeActivity == null ? null : homeActivity.realActivity; 20632 } 20633 } 20634 } 20635 20636 private final class SleepTokenImpl extends SleepToken { 20637 private final String mTag; 20638 private final long mAcquireTime; 20639 SleepTokenImpl(String tag)20640 public SleepTokenImpl(String tag) { 20641 mTag = tag; 20642 mAcquireTime = SystemClock.uptimeMillis(); 20643 } 20644 20645 @Override release()20646 public void release() { 20647 synchronized (ActivityManagerService.this) { 20648 if (mSleepTokens.remove(this)) { 20649 updateSleepIfNeededLocked(); 20650 } 20651 } 20652 } 20653 20654 @Override toString()20655 public String toString() { 20656 return "{\"" + mTag + "\", acquire at " + TimeUtils.formatUptime(mAcquireTime) + "}"; 20657 } 20658 } 20659 20660 /** 20661 * An implementation of IAppTask, that allows an app to manage its own tasks via 20662 * {@link android.app.ActivityManager.AppTask}. We keep track of the callingUid to ensure that 20663 * only the process that calls getAppTasks() can call the AppTask methods. 20664 */ 20665 class AppTaskImpl extends IAppTask.Stub { 20666 private int mTaskId; 20667 private int mCallingUid; 20668 AppTaskImpl(int taskId, int callingUid)20669 public AppTaskImpl(int taskId, int callingUid) { 20670 mTaskId = taskId; 20671 mCallingUid = callingUid; 20672 } 20673 checkCaller()20674 private void checkCaller() { 20675 if (mCallingUid != Binder.getCallingUid()) { 20676 throw new SecurityException("Caller " + mCallingUid 20677 + " does not match caller of getAppTasks(): " + Binder.getCallingUid()); 20678 } 20679 } 20680 20681 @Override finishAndRemoveTask()20682 public void finishAndRemoveTask() { 20683 checkCaller(); 20684 20685 synchronized (ActivityManagerService.this) { 20686 long origId = Binder.clearCallingIdentity(); 20687 try { 20688 if (!removeTaskByIdLocked(mTaskId, false)) { 20689 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 20690 } 20691 } finally { 20692 Binder.restoreCallingIdentity(origId); 20693 } 20694 } 20695 } 20696 20697 @Override getTaskInfo()20698 public ActivityManager.RecentTaskInfo getTaskInfo() { 20699 checkCaller(); 20700 20701 synchronized (ActivityManagerService.this) { 20702 long origId = Binder.clearCallingIdentity(); 20703 try { 20704 TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(mTaskId); 20705 if (tr == null) { 20706 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 20707 } 20708 return createRecentTaskInfoFromTaskRecord(tr); 20709 } finally { 20710 Binder.restoreCallingIdentity(origId); 20711 } 20712 } 20713 } 20714 20715 @Override moveToFront()20716 public void moveToFront() { 20717 checkCaller(); 20718 // Will bring task to front if it already has a root activity. 20719 startActivityFromRecentsInner(mTaskId, null); 20720 } 20721 20722 @Override startActivity(IBinder whoThread, String callingPackage, Intent intent, String resolvedType, Bundle options)20723 public int startActivity(IBinder whoThread, String callingPackage, 20724 Intent intent, String resolvedType, Bundle options) { 20725 checkCaller(); 20726 20727 int callingUser = UserHandle.getCallingUserId(); 20728 TaskRecord tr; 20729 IApplicationThread appThread; 20730 synchronized (ActivityManagerService.this) { 20731 tr = mStackSupervisor.anyTaskForIdLocked(mTaskId); 20732 if (tr == null) { 20733 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 20734 } 20735 appThread = ApplicationThreadNative.asInterface(whoThread); 20736 if (appThread == null) { 20737 throw new IllegalArgumentException("Bad app thread " + appThread); 20738 } 20739 } 20740 return mStackSupervisor.startActivityMayWait(appThread, -1, callingPackage, intent, 20741 resolvedType, null, null, null, null, 0, 0, null, null, 20742 null, options, false, callingUser, null, tr); 20743 } 20744 20745 @Override setExcludeFromRecents(boolean exclude)20746 public void setExcludeFromRecents(boolean exclude) { 20747 checkCaller(); 20748 20749 synchronized (ActivityManagerService.this) { 20750 long origId = Binder.clearCallingIdentity(); 20751 try { 20752 TaskRecord tr = mStackSupervisor.anyTaskForIdLocked(mTaskId); 20753 if (tr == null) { 20754 throw new IllegalArgumentException("Unable to find task ID " + mTaskId); 20755 } 20756 Intent intent = tr.getBaseIntent(); 20757 if (exclude) { 20758 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 20759 } else { 20760 intent.setFlags(intent.getFlags() 20761 & ~Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); 20762 } 20763 } finally { 20764 Binder.restoreCallingIdentity(origId); 20765 } 20766 } 20767 } 20768 } 20769 } 20770