blob: cc3b43adcacd06a56a9a7b5ce90e2865cc645aaa [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 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
17package com.android.server;
18
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -070019import android.app.IActivityController;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.content.BroadcastReceiver;
21import android.content.ContentResolver;
22import android.content.Context;
23import android.content.Intent;
24import android.content.IntentFilter;
Steven Moreland6b47c542017-03-21 12:52:16 -070025import android.hidl.manager.V1_0.IServiceManager;
Makoto Onuki99029542018-08-27 17:23:09 -070026import android.os.Binder;
27import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.os.Debug;
29import android.os.Handler;
Jeff Brown6f357d32014-01-15 20:40:55 -080030import android.os.IPowerManager;
John Michelau11641522013-03-18 18:28:23 -050031import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.os.Process;
Makoto Onuki99029542018-08-27 17:23:09 -070033import android.os.RemoteException;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080034import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.SystemClock;
Makoto Onuki99029542018-08-27 17:23:09 -070036import android.system.ErrnoException;
37import android.system.Os;
38import android.system.OsConstants;
39import android.system.StructRlimit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.util.EventLog;
Dan Egnor9bdc94b2010-03-04 14:20:31 -080041import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080042import android.util.Slog;
jianjin8f2dee02019-03-29 14:03:08 -070043import android.util.StatsLog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044
Makoto Onuki99029542018-08-27 17:23:09 -070045import com.android.internal.os.ZygoteConnectionConstants;
46import com.android.server.am.ActivityManagerService;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -080047import com.android.server.wm.SurfaceAnimationThread;
Makoto Onuki99029542018-08-27 17:23:09 -070048
Dan Egnor9bdc94b2010-03-04 14:20:31 -080049import java.io.File;
Colin Cross5df1d872012-11-29 11:42:11 -080050import java.io.FileWriter;
51import java.io.IOException;
Nandana Dutt6647ef52018-07-12 17:02:57 +010052import java.nio.charset.StandardCharsets;
53import java.nio.file.Files;
54import java.nio.file.Path;
55import java.nio.file.Paths;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import java.util.ArrayList;
Steven Moreland6b47c542017-03-21 12:52:16 -070057import java.util.Arrays;
Narayan Kamatha0a28082017-07-31 15:58:59 +010058import java.util.Collections;
Steven Moreland6b47c542017-03-21 12:52:16 -070059import java.util.HashSet;
60import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061
62/** This class calls its monitor every minute. Killing this process if they don't return **/
63public class Watchdog extends Thread {
64 static final String TAG = "Watchdog";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
Makoto Onukie276b442018-08-30 09:38:44 -070066 /** Debug flag. */
67 public static final boolean DEBUG = true; // STOPSHIP disable it (b/113252928)
Makoto Onuki99029542018-08-27 17:23:09 -070068
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069 // Set this to true to use debug default values.
70 static final boolean DB = false;
71
Andreas Gampe032a9292017-07-21 11:41:00 -070072 // Note 1: Do not lower this value below thirty seconds without tightening the invoke-with
73 // timeout in com.android.internal.os.ZygoteConnection, or wrapped applications
74 // can trigger the watchdog.
75 // Note 2: The debug value is already below the wait time in ZygoteConnection. Wrapped
76 // applications may not work with a debug build. CTS will fail.
Christopher Tatee6f81cf2013-10-23 17:28:27 -070077 static final long DEFAULT_TIMEOUT = DB ? 10*1000 : 60*1000;
78 static final long CHECK_INTERVAL = DEFAULT_TIMEOUT / 2;
79
80 // These are temporally ordered: larger values as lateness increases
81 static final int COMPLETED = 0;
82 static final int WAITING = 1;
83 static final int WAITED_HALF = 2;
84 static final int OVERDUE = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
Igor Murashkin44d04aa2013-10-23 10:56:02 -070086 // Which native processes to dump into dropbox's stack traces
87 public static final String[] NATIVE_STACKS_OF_INTEREST = new String[] {
Andy Hung3a64ecb2016-03-09 13:55:58 -080088 "/system/bin/audioserver",
Andy Hung689574a2016-04-13 19:27:43 -070089 "/system/bin/cameraserver",
90 "/system/bin/drmserver",
91 "/system/bin/mediadrmserver",
Dianne Hackbornf72467a2012-06-08 17:23:59 -070092 "/system/bin/mediaserver",
93 "/system/bin/sdcard",
Eric Laurent05d4e352016-03-14 18:49:08 -070094 "/system/bin/surfaceflinger",
Jeff Sharkey3e40afb2019-01-02 09:21:24 -070095 "/system/bin/vold",
Andy Hung689574a2016-04-13 19:27:43 -070096 "media.extractor", // system/bin/mediaextractor
Andy Hungb1c4c932018-01-04 12:05:43 -080097 "media.metrics", // system/bin/mediametrics
Chong Zhange55e6e02017-06-02 10:52:04 -070098 "media.codec", // vendor/bin/hw/android.hardware.media.omx@1.0-service
Andreas Gampecf9e79b2016-05-11 18:41:25 -070099 "com.android.bluetooth", // Bluetooth service
Rafal Slawike35d8f82018-10-01 11:39:58 +0100100 "/system/bin/statsd", // Stats daemon
Dianne Hackbornf72467a2012-06-08 17:23:59 -0700101 };
102
Steven Moreland6b47c542017-03-21 12:52:16 -0700103 public static final List<String> HAL_INTERFACES_OF_INTEREST = Arrays.asList(
Hui Yu7e65c3f2019-04-16 17:03:16 -0700104 "android.hardware.audio@2.0::IDevicesFactory",
105 "android.hardware.audio@4.0::IDevicesFactory",
106 "android.hardware.bluetooth@1.0::IBluetoothHci",
107 "android.hardware.camera.provider@2.4::ICameraProvider",
108 "android.hardware.graphics.allocator@2.0::IAllocator",
109 "android.hardware.graphics.composer@2.1::IComposer",
110 "android.hardware.health@2.0::IHealth",
111 "android.hardware.media.omx@1.0::IOmx",
112 "android.hardware.media.omx@1.0::IOmxStore",
113 "android.hardware.sensors@1.0::ISensors",
114 "android.hardware.vr@1.0::IVr",
115 "android.hardware.biometrics.face@1.0::IBiometricsFace"
Steven Moreland6b47c542017-03-21 12:52:16 -0700116 );
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 static Watchdog sWatchdog;
119
120 /* This handler will be used to post message back onto the main thread */
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700121 final ArrayList<HandlerChecker> mHandlerCheckers = new ArrayList<>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700122 final HandlerChecker mMonitorChecker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 ContentResolver mResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 ActivityManagerService mActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 int mPhonePid;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700127 IActivityController mController;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700128 boolean mAllowRestart = true;
Narayan Kamatha0a28082017-07-31 15:58:59 +0100129 final OpenFdMonitor mOpenFdMonitor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 /**
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700132 * Used for checking status of handle threads and scheduling monitor callbacks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700134 public final class HandlerChecker implements Runnable {
135 private final Handler mHandler;
136 private final String mName;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700137 private final long mWaitMax;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700138 private final ArrayList<Monitor> mMonitors = new ArrayList<Monitor>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700139 private boolean mCompleted;
140 private Monitor mCurrentMonitor;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700141 private long mStartTime;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700142
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700143 HandlerChecker(Handler handler, String name, long waitMaxMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700144 mHandler = handler;
145 mName = name;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700146 mWaitMax = waitMaxMillis;
147 mCompleted = true;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700148 }
149
Makoto Onukie276b442018-08-30 09:38:44 -0700150 void addMonitorLocked(Monitor monitor) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700151 mMonitors.add(monitor);
152 }
153
154 public void scheduleCheckLocked() {
Jeff Brown6c7b41a2015-02-26 14:43:53 -0800155 if (mMonitors.size() == 0 && mHandler.getLooper().getQueue().isPolling()) {
156 // If the target looper has recently been polling, then
Dianne Hackbornefa92b22013-05-03 14:11:43 -0700157 // there is no reason to enqueue our checker on it since that
158 // is as good as it not being deadlocked. This avoid having
159 // to do a context switch to check the thread. Note that we
160 // only do this if mCheckReboot is false and we have no
161 // monitors, since those would need to be executed at this point.
162 mCompleted = true;
163 return;
164 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700165
166 if (!mCompleted) {
167 // we already have a check in flight, so no need
168 return;
169 }
170
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700171 mCompleted = false;
172 mCurrentMonitor = null;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700173 mStartTime = SystemClock.uptimeMillis();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700174 mHandler.postAtFrontOfQueue(this);
175 }
176
Makoto Onukie276b442018-08-30 09:38:44 -0700177 boolean isOverdueLocked() {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700178 return (!mCompleted) && (SystemClock.uptimeMillis() > mStartTime + mWaitMax);
179 }
180
181 public int getCompletionStateLocked() {
182 if (mCompleted) {
183 return COMPLETED;
184 } else {
185 long latency = SystemClock.uptimeMillis() - mStartTime;
186 if (latency < mWaitMax/2) {
187 return WAITING;
188 } else if (latency < mWaitMax) {
189 return WAITED_HALF;
190 }
191 }
192 return OVERDUE;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700193 }
194
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700195 public Thread getThread() {
196 return mHandler.getLooper().getThread();
197 }
198
199 public String getName() {
200 return mName;
201 }
202
Makoto Onukie276b442018-08-30 09:38:44 -0700203 String describeBlockedStateLocked() {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700204 if (mCurrentMonitor == null) {
205 return "Blocked in handler on " + mName + " (" + getThread().getName() + ")";
206 } else {
207 return "Blocked in monitor " + mCurrentMonitor.getClass().getName()
208 + " on " + mName + " (" + getThread().getName() + ")";
209 }
John Michelau11641522013-03-18 18:28:23 -0500210 }
211
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212 @Override
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700213 public void run() {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700214 final int size = mMonitors.size();
215 for (int i = 0 ; i < size ; i++) {
216 synchronized (Watchdog.this) {
217 mCurrentMonitor = mMonitors.get(i);
218 }
219 mCurrentMonitor.monitor();
220 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700222 synchronized (Watchdog.this) {
223 mCompleted = true;
224 mCurrentMonitor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 }
226 }
227 }
228
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 final class RebootRequestReceiver extends BroadcastReceiver {
230 @Override
231 public void onReceive(Context c, Intent intent) {
Dianne Hackbornf6438b12013-05-09 18:53:48 -0700232 if (intent.getIntExtra("nowait", 0) != 0) {
233 rebootSystem("Received ACTION_REBOOT broadcast");
234 return;
235 }
236 Slog.w(TAG, "Unsupported ACTION_REBOOT broadcast: " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237 }
238 }
239
Wale Ogunwale517daec2015-04-15 10:27:24 -0700240 /** Monitor for checking the availability of binder threads. The monitor will block until
241 * there is a binder thread available to process in coming IPCs to make sure other processes
242 * can still communicate with the service.
243 */
244 private static final class BinderThreadMonitor implements Watchdog.Monitor {
245 @Override
246 public void monitor() {
247 Binder.blockUntilThreadAvailable();
248 }
249 }
250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800251 public interface Monitor {
252 void monitor();
253 }
254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800255 public static Watchdog getInstance() {
256 if (sWatchdog == null) {
257 sWatchdog = new Watchdog();
258 }
259
260 return sWatchdog;
261 }
262
263 private Watchdog() {
264 super("watchdog");
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700265 // Initialize handler checkers for each common thread we want to check. Note
266 // that we are not currently checking the background thread, since it can
267 // potentially hold longer running operations with no guarantees about the timeliness
268 // of operations there.
269
270 // The shared foreground thread is the main checker. It is where we
271 // will also dispatch monitor checks and do other work.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700272 mMonitorChecker = new HandlerChecker(FgThread.getHandler(),
273 "foreground thread", DEFAULT_TIMEOUT);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700274 mHandlerCheckers.add(mMonitorChecker);
275 // Add checker for main thread. We only do a quick check since there
276 // can be UI running on the thread.
277 mHandlerCheckers.add(new HandlerChecker(new Handler(Looper.getMainLooper()),
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700278 "main thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700279 // Add checker for shared UI thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700280 mHandlerCheckers.add(new HandlerChecker(UiThread.getHandler(),
281 "ui thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700282 // And also check IO thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700283 mHandlerCheckers.add(new HandlerChecker(IoThread.getHandler(),
284 "i/o thread", DEFAULT_TIMEOUT));
Jeff Brown4ccb8232014-01-16 22:16:42 -0800285 // And the display thread.
286 mHandlerCheckers.add(new HandlerChecker(DisplayThread.getHandler(),
287 "display thread", DEFAULT_TIMEOUT));
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800288 // And the animation thread.
289 mHandlerCheckers.add(new HandlerChecker(AnimationThread.getHandler(),
290 "animation thread", DEFAULT_TIMEOUT));
291 // And the surface animation thread.
292 mHandlerCheckers.add(new HandlerChecker(SurfaceAnimationThread.getHandler(),
293 "surface animation thread", DEFAULT_TIMEOUT));
Wale Ogunwale517daec2015-04-15 10:27:24 -0700294
295 // Initialize monitor for Binder threads.
296 addMonitor(new BinderThreadMonitor());
Andreas Gampe032a9292017-07-21 11:41:00 -0700297
Narayan Kamatha0a28082017-07-31 15:58:59 +0100298 mOpenFdMonitor = OpenFdMonitor.create();
299
Andreas Gampe032a9292017-07-21 11:41:00 -0700300 // See the notes on DEFAULT_TIMEOUT.
301 assert DB ||
302 DEFAULT_TIMEOUT > ZygoteConnectionConstants.WRAPPED_PID_TIMEOUT_MILLIS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 }
304
Adam Lesinski182f73f2013-12-05 16:48:06 -0800305 public void init(Context context, ActivityManagerService activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 mResolver = context.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 mActivity = activity;
308
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800309 context.registerReceiver(new RebootRequestReceiver(),
310 new IntentFilter(Intent.ACTION_REBOOT),
311 android.Manifest.permission.REBOOT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800312 }
313
Christopher Tatec27181c2010-06-30 14:41:09 -0700314 public void processStarted(String name, int pid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 synchronized (this) {
316 if ("com.android.phone".equals(name)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800317 mPhonePid = pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800318 }
319 }
320 }
321
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700322 public void setActivityController(IActivityController controller) {
323 synchronized (this) {
324 mController = controller;
325 }
326 }
327
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700328 public void setAllowRestart(boolean allowRestart) {
329 synchronized (this) {
330 mAllowRestart = allowRestart;
331 }
332 }
333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800334 public void addMonitor(Monitor monitor) {
335 synchronized (this) {
336 if (isAlive()) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700337 throw new RuntimeException("Monitors can't be added once the Watchdog is running");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338 }
Makoto Onukie276b442018-08-30 09:38:44 -0700339 mMonitorChecker.addMonitorLocked(monitor);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700340 }
341 }
342
Jeff Brown6f357d32014-01-15 20:40:55 -0800343 public void addThread(Handler thread) {
344 addThread(thread, DEFAULT_TIMEOUT);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700345 }
346
Jeff Brown6f357d32014-01-15 20:40:55 -0800347 public void addThread(Handler thread, long timeoutMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700348 synchronized (this) {
349 if (isAlive()) {
350 throw new RuntimeException("Threads can't be added once the Watchdog is running");
351 }
Jeff Brown6f357d32014-01-15 20:40:55 -0800352 final String name = thread.getLooper().getThread().getName();
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700353 mHandlerCheckers.add(new HandlerChecker(thread, name, timeoutMillis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800354 }
355 }
356
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800357 /**
358 * Perform a full reboot of the system.
359 */
360 void rebootSystem(String reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800361 Slog.i(TAG, "Rebooting system because: " + reason);
Jeff Brown6f357d32014-01-15 20:40:55 -0800362 IPowerManager pms = (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE);
363 try {
364 pms.reboot(false, reason, false);
365 } catch (RemoteException ex) {
366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800367 }
368
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700369 private int evaluateCheckerCompletionLocked() {
370 int state = COMPLETED;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700371 for (int i=0; i<mHandlerCheckers.size(); i++) {
372 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700373 state = Math.max(state, hc.getCompletionStateLocked());
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700374 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700375 return state;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700376 }
377
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700378 private ArrayList<HandlerChecker> getBlockedCheckersLocked() {
379 ArrayList<HandlerChecker> checkers = new ArrayList<HandlerChecker>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700380 for (int i=0; i<mHandlerCheckers.size(); i++) {
381 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700382 if (hc.isOverdueLocked()) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700383 checkers.add(hc);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700384 }
385 }
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700386 return checkers;
387 }
388
Narayan Kamatha0a28082017-07-31 15:58:59 +0100389 private String describeCheckersLocked(List<HandlerChecker> checkers) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700390 StringBuilder builder = new StringBuilder(128);
391 for (int i=0; i<checkers.size(); i++) {
392 if (builder.length() > 0) {
393 builder.append(", ");
394 }
395 builder.append(checkers.get(i).describeBlockedStateLocked());
396 }
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700397 return builder.toString();
398 }
399
Hui Yu7e65c3f2019-04-16 17:03:16 -0700400 private static ArrayList<Integer> getInterestingHalPids() {
Steven Moreland6b47c542017-03-21 12:52:16 -0700401 try {
402 IServiceManager serviceManager = IServiceManager.getService();
403 ArrayList<IServiceManager.InstanceDebugInfo> dump =
404 serviceManager.debugDump();
405 HashSet<Integer> pids = new HashSet<>();
406 for (IServiceManager.InstanceDebugInfo info : dump) {
407 if (info.pid == IServiceManager.PidConstant.NO_PID) {
408 continue;
409 }
410
411 if (!HAL_INTERFACES_OF_INTEREST.contains(info.interfaceName)) {
412 continue;
413 }
414
415 pids.add(info.pid);
416 }
417 return new ArrayList<Integer>(pids);
418 } catch (RemoteException e) {
419 return new ArrayList<Integer>();
420 }
421 }
422
Hui Yu7e65c3f2019-04-16 17:03:16 -0700423 static ArrayList<Integer> getInterestingNativePids() {
Steven Moreland6b47c542017-03-21 12:52:16 -0700424 ArrayList<Integer> pids = getInterestingHalPids();
425
426 int[] nativePids = Process.getPidsForCommands(NATIVE_STACKS_OF_INTEREST);
427 if (nativePids != null) {
428 pids.ensureCapacity(pids.size() + nativePids.length);
429 for (int i : nativePids) {
430 pids.add(i);
431 }
432 }
433
434 return pids;
435 }
436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800437 @Override
438 public void run() {
Christopher Tate6ee412d2010-05-28 12:01:56 -0700439 boolean waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 while (true) {
Narayan Kamatha0a28082017-07-31 15:58:59 +0100441 final List<HandlerChecker> blockedCheckers;
Jeff Brown7dd2d192013-09-06 15:05:23 -0700442 final String subject;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700443 final boolean allowRestart;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700444 int debuggerWasConnected = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800445 synchronized (this) {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700446 long timeout = CHECK_INTERVAL;
447 // Make sure we (re)spin the checkers that have become idle within
448 // this wait-and-check interval
449 for (int i=0; i<mHandlerCheckers.size(); i++) {
450 HandlerChecker hc = mHandlerCheckers.get(i);
451 hc.scheduleCheckLocked();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700454 if (debuggerWasConnected > 0) {
455 debuggerWasConnected--;
456 }
457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 // NOTE: We use uptimeMillis() here because we do not want to increment the time we
459 // wait while asleep. If the device is asleep then the thing that we are waiting
Christopher Tate6ee412d2010-05-28 12:01:56 -0700460 // to timeout on is asleep as well and won't have a chance to run, causing a false
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800461 // positive on when to kill things.
462 long start = SystemClock.uptimeMillis();
Michael Wright8fa56f62013-04-01 16:36:05 -0700463 while (timeout > 0) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700464 if (Debug.isDebuggerConnected()) {
465 debuggerWasConnected = 2;
466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 try {
Michael Wright8fa56f62013-04-01 16:36:05 -0700468 wait(timeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 } catch (InterruptedException e) {
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800470 Log.wtf(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700472 if (Debug.isDebuggerConnected()) {
473 debuggerWasConnected = 2;
474 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700475 timeout = CHECK_INTERVAL - (SystemClock.uptimeMillis() - start);
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800476 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800477
Narayan Kamatha0a28082017-07-31 15:58:59 +0100478 boolean fdLimitTriggered = false;
479 if (mOpenFdMonitor != null) {
480 fdLimitTriggered = mOpenFdMonitor.monitor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800481 }
Michael Wright8fa56f62013-04-01 16:36:05 -0700482
Narayan Kamatha0a28082017-07-31 15:58:59 +0100483 if (!fdLimitTriggered) {
484 final int waitState = evaluateCheckerCompletionLocked();
485 if (waitState == COMPLETED) {
486 // The monitors have returned; reset
487 waitedHalf = false;
488 continue;
489 } else if (waitState == WAITING) {
490 // still waiting but within their configured intervals; back off and recheck
491 continue;
492 } else if (waitState == WAITED_HALF) {
493 if (!waitedHalf) {
Makoto Onuki99029542018-08-27 17:23:09 -0700494 if (DEBUG) Slog.d(TAG, "WAITED_HALF");
Narayan Kamatha0a28082017-07-31 15:58:59 +0100495 // We've waited half the deadlock-detection interval. Pull a stack
496 // trace and wait another half.
497 ArrayList<Integer> pids = new ArrayList<Integer>();
498 pids.add(Process.myPid());
Makoto Onukie276b442018-08-30 09:38:44 -0700499 ActivityManagerService.dumpStackTraces(pids, null, null,
Narayan Kamatha0a28082017-07-31 15:58:59 +0100500 getInterestingNativePids());
501 waitedHalf = true;
502 }
503 continue;
504 }
505
506 // something is overdue!
507 blockedCheckers = getBlockedCheckersLocked();
508 subject = describeCheckersLocked(blockedCheckers);
509 } else {
510 blockedCheckers = Collections.emptyList();
511 subject = "Open FD high water mark reached";
512 }
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700513 allowRestart = mAllowRestart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800514 }
515
516 // If we got here, that means that the system is most likely hung.
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700517 // First collect stack traces from all threads of the system process.
518 // Then kill this process so that the system will restart.
Jeff Brown7dd2d192013-09-06 15:05:23 -0700519 EventLog.writeEvent(EventLogTags.WATCHDOG, subject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520
Steven Moreland6b47c542017-03-21 12:52:16 -0700521 ArrayList<Integer> pids = new ArrayList<>();
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800522 pids.add(Process.myPid());
Dan Egnor4bded072010-03-11 22:00:47 -0800523 if (mPhonePid > 0) pids.add(mPhonePid);
Makoto Onukie276b442018-08-30 09:38:44 -0700524
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800525 final File stack = ActivityManagerService.dumpStackTraces(
Makoto Onukie276b442018-08-30 09:38:44 -0700526 pids, null, null, getInterestingNativePids());
Dan Egnor4bded072010-03-11 22:00:47 -0800527
528 // Give some extra time to make sure the stack traces get written.
529 // The system's been hanging for a minute, another second or two won't hurt much.
Makoto Onukie276b442018-08-30 09:38:44 -0700530 SystemClock.sleep(5000);
Dan Egnor4bded072010-03-11 22:00:47 -0800531
Guang Zhu0620c452014-10-29 14:31:48 -0700532 // Trigger the kernel to dump all blocked threads, and backtraces on all CPUs to the kernel log
533 doSysRq('w');
534 doSysRq('l');
Colin Cross5df1d872012-11-29 11:42:11 -0800535
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800536 // Try to add the error to the dropbox, but assuming that the ActivityManager
537 // itself may be deadlocked. (which has happened, causing this statement to
538 // deadlock and the watchdog as a whole to be ineffective)
539 Thread dropboxThread = new Thread("watchdogWriteToDropbox") {
540 public void run() {
541 mActivity.addErrorToDropBox(
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700542 "watchdog", null, "system_server", null, null, null,
Jeff Brown7dd2d192013-09-06 15:05:23 -0700543 subject, null, stack, null);
jianjin8f2dee02019-03-29 14:03:08 -0700544 StatsLog.write(StatsLog.SYSTEM_SERVER_WATCHDOG_OCCURRED, subject);
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800545 }
546 };
547 dropboxThread.start();
548 try {
549 dropboxThread.join(2000); // wait up to 2 seconds for it to return.
550 } catch (InterruptedException ignored) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800551
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700552 IActivityController controller;
553 synchronized (this) {
554 controller = mController;
555 }
556 if (controller != null) {
557 Slog.i(TAG, "Reporting stuck state to activity controller");
558 try {
559 Binder.setDumpDisabled("Service dumps disabled due to hung system process.");
560 // 1 = keep waiting, -1 = kill system
Jeff Brown7dd2d192013-09-06 15:05:23 -0700561 int res = controller.systemNotResponding(subject);
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700562 if (res >= 0) {
563 Slog.i(TAG, "Activity controller requested to coninue to wait");
564 waitedHalf = false;
565 continue;
566 }
567 } catch (RemoteException e) {
568 }
569 }
570
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700571 // Only kill the process if the debugger is not attached.
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700572 if (Debug.isDebuggerConnected()) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700573 debuggerWasConnected = 2;
574 }
575 if (debuggerWasConnected >= 2) {
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700576 Slog.w(TAG, "Debugger connected: Watchdog is *not* killing the system process");
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700577 } else if (debuggerWasConnected > 0) {
578 Slog.w(TAG, "Debugger was connected: Watchdog is *not* killing the system process");
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700579 } else if (!allowRestart) {
580 Slog.w(TAG, "Restart not allowed: Watchdog is *not* killing the system process");
581 } else {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700582 Slog.w(TAG, "*** WATCHDOG KILLING SYSTEM PROCESS: " + subject);
Andreas Gampe544416e2018-01-26 11:39:46 -0800583 WatchdogDiagnostics.diagnoseCheckers(blockedCheckers);
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700584 Slog.w(TAG, "*** GOODBYE!");
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700585 Process.killProcess(Process.myPid());
586 System.exit(10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 }
Christopher Tate6ee412d2010-05-28 12:01:56 -0700588
589 waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 }
591 }
Christopher Tateecaa7b42010-06-04 14:55:02 -0700592
Guang Zhu0620c452014-10-29 14:31:48 -0700593 private void doSysRq(char c) {
594 try {
595 FileWriter sysrq_trigger = new FileWriter("/proc/sysrq-trigger");
596 sysrq_trigger.write(c);
597 sysrq_trigger.close();
598 } catch (IOException e) {
599 Slog.w(TAG, "Failed to write to /proc/sysrq-trigger", e);
600 }
601 }
602
Narayan Kamatha0a28082017-07-31 15:58:59 +0100603 public static final class OpenFdMonitor {
604 /**
605 * Number of FDs below the soft limit that we trigger a runtime restart at. This was
606 * chosen arbitrarily, but will need to be at least 6 in order to have a sufficient number
607 * of FDs in reserve to complete a dump.
608 */
609 private static final int FD_HIGH_WATER_MARK = 12;
610
611 private final File mDumpDir;
612 private final File mFdHighWaterMark;
613
614 public static OpenFdMonitor create() {
615 // Only run the FD monitor on debuggable builds (such as userdebug and eng builds).
616 if (!Build.IS_DEBUGGABLE) {
617 return null;
618 }
619
Narayan Kamatha0a28082017-07-31 15:58:59 +0100620 final StructRlimit rlimit;
621 try {
622 rlimit = android.system.Os.getrlimit(OsConstants.RLIMIT_NOFILE);
623 } catch (ErrnoException errno) {
624 Slog.w(TAG, "Error thrown from getrlimit(RLIMIT_NOFILE)", errno);
625 return null;
626 }
627
628 // The assumption we're making here is that FD numbers are allocated (more or less)
629 // sequentially, which is currently (and historically) true since open is currently
630 // specified to always return the lowest-numbered non-open file descriptor for the
631 // current process.
632 //
633 // We do this to avoid having to enumerate the contents of /proc/self/fd in order to
634 // count the number of descriptors open in the process.
635 final File fdThreshold = new File("/proc/self/fd/" + (rlimit.rlim_cur - FD_HIGH_WATER_MARK));
Elliott Hughes4e4caa72018-03-23 11:06:36 -0700636 return new OpenFdMonitor(new File("/data/anr"), fdThreshold);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100637 }
638
639 OpenFdMonitor(File dumpDir, File fdThreshold) {
640 mDumpDir = dumpDir;
641 mFdHighWaterMark = fdThreshold;
642 }
643
Nandana Dutt6647ef52018-07-12 17:02:57 +0100644 /**
645 * Dumps open file descriptors and their full paths to a temporary file in {@code mDumpDir}.
646 */
Narayan Kamatha0a28082017-07-31 15:58:59 +0100647 private void dumpOpenDescriptors() {
Nandana Dutt6647ef52018-07-12 17:02:57 +0100648 // We cannot exec lsof to get more info about open file descriptors because a newly
649 // forked process will not have the permissions to readlink. Instead list all open
650 // descriptors from /proc/pid/fd and resolve them.
651 List<String> dumpInfo = new ArrayList<>();
652 String fdDirPath = String.format("/proc/%d/fd/", Process.myPid());
653 File[] fds = new File(fdDirPath).listFiles();
654 if (fds == null) {
655 dumpInfo.add("Unable to list " + fdDirPath);
656 } else {
657 for (File f : fds) {
658 String fdSymLink = f.getAbsolutePath();
659 String resolvedPath = "";
660 try {
661 resolvedPath = Os.readlink(fdSymLink);
662 } catch (ErrnoException ex) {
663 resolvedPath = ex.getMessage();
664 }
665 dumpInfo.add(fdSymLink + "\t" + resolvedPath);
666 }
667 }
668
669 // Dump the fds & paths to a temp file.
Narayan Kamatha0a28082017-07-31 15:58:59 +0100670 try {
671 File dumpFile = File.createTempFile("anr_fd_", "", mDumpDir);
Nandana Dutt6647ef52018-07-12 17:02:57 +0100672 Path out = Paths.get(dumpFile.getAbsolutePath());
673 Files.write(out, dumpInfo, StandardCharsets.UTF_8);
674 } catch (IOException ex) {
675 Slog.w(TAG, "Unable to write open descriptors to file: " + ex);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100676 }
677 }
678
679 /**
680 * @return {@code true} if the high water mark was breached and a dump was written,
681 * {@code false} otherwise.
682 */
683 public boolean monitor() {
684 if (mFdHighWaterMark.exists()) {
685 dumpOpenDescriptors();
686 return true;
687 }
688
689 return false;
690 }
691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800692}