blob: 19ad32e202fe1dd80a446b56848a4d536d671fa0 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
Steven Moreland6b47c542017-03-21 12:52:16 -070024import android.hidl.manager.V1_0.IServiceManager;
Makoto Onuki99029542018-08-27 17:23:09 -070025import android.os.Binder;
26import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.os.Debug;
28import android.os.Handler;
Jeff Brown6f357d32014-01-15 20:40:55 -080029import android.os.IPowerManager;
John Michelau11641522013-03-18 18:28:23 -050030import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.os.Process;
Makoto Onuki99029542018-08-27 17:23:09 -070032import android.os.RemoteException;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080033import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.os.SystemClock;
Makoto Onuki99029542018-08-27 17:23:09 -070035import android.system.ErrnoException;
36import android.system.Os;
37import android.system.OsConstants;
38import android.system.StructRlimit;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.util.EventLog;
Dan Egnor9bdc94b2010-03-04 14:20:31 -080040import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080041import android.util.Slog;
jianjin8f2dee02019-03-29 14:03:08 -070042import android.util.StatsLog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043
Makoto Onuki99029542018-08-27 17:23:09 -070044import com.android.internal.os.ZygoteConnectionConstants;
45import com.android.server.am.ActivityManagerService;
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -080046import com.android.server.wm.SurfaceAnimationThread;
Makoto Onuki99029542018-08-27 17:23:09 -070047
Dan Egnor9bdc94b2010-03-04 14:20:31 -080048import java.io.File;
Colin Cross5df1d872012-11-29 11:42:11 -080049import java.io.FileWriter;
50import java.io.IOException;
Nandana Dutt6647ef52018-07-12 17:02:57 +010051import java.nio.charset.StandardCharsets;
52import java.nio.file.Files;
53import java.nio.file.Path;
54import java.nio.file.Paths;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import java.util.ArrayList;
Steven Moreland6b47c542017-03-21 12:52:16 -070056import java.util.Arrays;
Narayan Kamatha0a28082017-07-31 15:58:59 +010057import java.util.Collections;
Steven Moreland6b47c542017-03-21 12:52:16 -070058import java.util.HashSet;
59import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
61/** This class calls its monitor every minute. Killing this process if they don't return **/
62public class Watchdog extends Thread {
63 static final String TAG = "Watchdog";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064
Makoto Onukie276b442018-08-30 09:38:44 -070065 /** Debug flag. */
Makoto Onuki729c41e2019-05-30 09:47:10 -070066 public static final boolean DEBUG = false;
Makoto Onuki99029542018-08-27 17:23:09 -070067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068 // Set this to true to use debug default values.
69 static final boolean DB = false;
70
Andreas Gampe032a9292017-07-21 11:41:00 -070071 // Note 1: Do not lower this value below thirty seconds without tightening the invoke-with
72 // timeout in com.android.internal.os.ZygoteConnection, or wrapped applications
73 // can trigger the watchdog.
74 // Note 2: The debug value is already below the wait time in ZygoteConnection. Wrapped
75 // applications may not work with a debug build. CTS will fail.
Christopher Tatee6f81cf2013-10-23 17:28:27 -070076 static final long DEFAULT_TIMEOUT = DB ? 10*1000 : 60*1000;
77 static final long CHECK_INTERVAL = DEFAULT_TIMEOUT / 2;
78
79 // These are temporally ordered: larger values as lateness increases
80 static final int COMPLETED = 0;
81 static final int WAITING = 1;
82 static final int WAITED_HALF = 2;
83 static final int OVERDUE = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
Igor Murashkin44d04aa2013-10-23 10:56:02 -070085 // Which native processes to dump into dropbox's stack traces
86 public static final String[] NATIVE_STACKS_OF_INTEREST = new String[] {
Andy Hung3a64ecb2016-03-09 13:55:58 -080087 "/system/bin/audioserver",
Andy Hung689574a2016-04-13 19:27:43 -070088 "/system/bin/cameraserver",
89 "/system/bin/drmserver",
90 "/system/bin/mediadrmserver",
Dianne Hackbornf72467a2012-06-08 17:23:59 -070091 "/system/bin/mediaserver",
92 "/system/bin/sdcard",
Eric Laurent05d4e352016-03-14 18:49:08 -070093 "/system/bin/surfaceflinger",
Jeff Sharkey3e40afb2019-01-02 09:21:24 -070094 "/system/bin/vold",
Andy Hung689574a2016-04-13 19:27:43 -070095 "media.extractor", // system/bin/mediaextractor
Andy Hungb1c4c932018-01-04 12:05:43 -080096 "media.metrics", // system/bin/mediametrics
Chong Zhange55e6e02017-06-02 10:52:04 -070097 "media.codec", // vendor/bin/hw/android.hardware.media.omx@1.0-service
Chong Zhangf1f76322019-03-27 16:41:51 -070098 "media.swcodec", // /apex/com.android.media.swcodec/bin/mediaswcodec
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",
Kevin Chyn7733b752019-06-19 13:48:18 -0700106 "android.hardware.biometrics.face@1.0::IBiometricsFace",
Hui Yu7e65c3f2019-04-16 17:03:16 -0700107 "android.hardware.bluetooth@1.0::IBluetoothHci",
108 "android.hardware.camera.provider@2.4::ICameraProvider",
109 "android.hardware.graphics.allocator@2.0::IAllocator",
110 "android.hardware.graphics.composer@2.1::IComposer",
111 "android.hardware.health@2.0::IHealth",
Chong Zhangf1f76322019-03-27 16:41:51 -0700112 "android.hardware.media.c2@1.0::IComponentStore",
Hui Yu7e65c3f2019-04-16 17:03:16 -0700113 "android.hardware.media.omx@1.0::IOmx",
114 "android.hardware.media.omx@1.0::IOmxStore",
Benjamin Schwartzf0a81f62019-06-18 17:58:39 -0700115 "android.hardware.power.stats@1.0::IPowerStats",
Hui Yu7e65c3f2019-04-16 17:03:16 -0700116 "android.hardware.sensors@1.0::ISensors",
Kalesh Singh5fe631d2019-07-02 13:51:53 -0700117 "android.hardware.vr@1.0::IVr",
118 "android.system.suspend@1.0::ISystemSuspend"
Steven Moreland6b47c542017-03-21 12:52:16 -0700119 );
120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 static Watchdog sWatchdog;
122
123 /* This handler will be used to post message back onto the main thread */
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700124 final ArrayList<HandlerChecker> mHandlerCheckers = new ArrayList<>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700125 final HandlerChecker mMonitorChecker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 ActivityManagerService mActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 int mPhonePid;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700129 IActivityController mController;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700130 boolean mAllowRestart = true;
Narayan Kamatha0a28082017-07-31 15:58:59 +0100131 final OpenFdMonitor mOpenFdMonitor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 /**
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700134 * Used for checking status of handle threads and scheduling monitor callbacks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700136 public final class HandlerChecker implements Runnable {
137 private final Handler mHandler;
138 private final String mName;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700139 private final long mWaitMax;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700140 private final ArrayList<Monitor> mMonitors = new ArrayList<Monitor>();
Zimuzob065b152019-04-16 13:33:01 +0100141 private final ArrayList<Monitor> mMonitorQueue = new ArrayList<Monitor>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700142 private boolean mCompleted;
143 private Monitor mCurrentMonitor;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700144 private long mStartTime;
Zimuzo2a050392019-05-09 12:51:33 +0100145 private int mPauseCount;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700146
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700147 HandlerChecker(Handler handler, String name, long waitMaxMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700148 mHandler = handler;
149 mName = name;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700150 mWaitMax = waitMaxMillis;
151 mCompleted = true;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700152 }
153
Makoto Onukie276b442018-08-30 09:38:44 -0700154 void addMonitorLocked(Monitor monitor) {
Zimuzob065b152019-04-16 13:33:01 +0100155 // We don't want to update mMonitors when the Handler is in the middle of checking
156 // all monitors. We will update mMonitors on the next schedule if it is safe
157 mMonitorQueue.add(monitor);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700158 }
159
160 public void scheduleCheckLocked() {
Zimuzob065b152019-04-16 13:33:01 +0100161 if (mCompleted) {
162 // Safe to update monitors in queue, Handler is not in the middle of work
163 mMonitors.addAll(mMonitorQueue);
164 mMonitorQueue.clear();
165 }
Zimuzo2a050392019-05-09 12:51:33 +0100166 if ((mMonitors.size() == 0 && mHandler.getLooper().getQueue().isPolling())
167 || (mPauseCount > 0)) {
168 // Don't schedule until after resume OR
Jeff Brown6c7b41a2015-02-26 14:43:53 -0800169 // If the target looper has recently been polling, then
Dianne Hackbornefa92b22013-05-03 14:11:43 -0700170 // there is no reason to enqueue our checker on it since that
171 // is as good as it not being deadlocked. This avoid having
Zimuzo2a050392019-05-09 12:51:33 +0100172 // to do a context switch to check the thread. Note that we
173 // only do this if we have no monitors since those would need to
174 // be executed at this point.
Dianne Hackbornefa92b22013-05-03 14:11:43 -0700175 mCompleted = true;
176 return;
177 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700178 if (!mCompleted) {
179 // we already have a check in flight, so no need
180 return;
181 }
182
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700183 mCompleted = false;
184 mCurrentMonitor = null;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700185 mStartTime = SystemClock.uptimeMillis();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700186 mHandler.postAtFrontOfQueue(this);
187 }
188
Makoto Onukie276b442018-08-30 09:38:44 -0700189 boolean isOverdueLocked() {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700190 return (!mCompleted) && (SystemClock.uptimeMillis() > mStartTime + mWaitMax);
191 }
192
193 public int getCompletionStateLocked() {
194 if (mCompleted) {
195 return COMPLETED;
196 } else {
197 long latency = SystemClock.uptimeMillis() - mStartTime;
198 if (latency < mWaitMax/2) {
199 return WAITING;
200 } else if (latency < mWaitMax) {
201 return WAITED_HALF;
202 }
203 }
204 return OVERDUE;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700205 }
206
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700207 public Thread getThread() {
208 return mHandler.getLooper().getThread();
209 }
210
211 public String getName() {
212 return mName;
213 }
214
Makoto Onukie276b442018-08-30 09:38:44 -0700215 String describeBlockedStateLocked() {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700216 if (mCurrentMonitor == null) {
217 return "Blocked in handler on " + mName + " (" + getThread().getName() + ")";
218 } else {
219 return "Blocked in monitor " + mCurrentMonitor.getClass().getName()
220 + " on " + mName + " (" + getThread().getName() + ")";
221 }
John Michelau11641522013-03-18 18:28:23 -0500222 }
223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 @Override
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700225 public void run() {
Zimuzob065b152019-04-16 13:33:01 +0100226 // Once we get here, we ensure that mMonitors does not change even if we call
227 // #addMonitorLocked because we first add the new monitors to mMonitorQueue and
228 // move them to mMonitors on the next schedule when mCompleted is true, at which
229 // point we have completed execution of this method.
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700230 final int size = mMonitors.size();
231 for (int i = 0 ; i < size ; i++) {
232 synchronized (Watchdog.this) {
233 mCurrentMonitor = mMonitors.get(i);
234 }
235 mCurrentMonitor.monitor();
236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700238 synchronized (Watchdog.this) {
239 mCompleted = true;
240 mCurrentMonitor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 }
242 }
Zimuzo2a050392019-05-09 12:51:33 +0100243
244 /** Pause the HandlerChecker. */
245 public void pauseLocked(String reason) {
246 mPauseCount++;
247 // Mark as completed, because there's a chance we called this after the watchog
248 // thread loop called Object#wait after 'WAITED_HALF'. In that case we want to ensure
249 // the next call to #getCompletionStateLocked for this checker returns 'COMPLETED'
250 mCompleted = true;
251 Slog.i(TAG, "Pausing HandlerChecker: " + mName + " for reason: "
252 + reason + ". Pause count: " + mPauseCount);
253 }
254
255 /** Resume the HandlerChecker from the last {@link #pauseLocked}. */
256 public void resumeLocked(String reason) {
257 if (mPauseCount > 0) {
258 mPauseCount--;
259 Slog.i(TAG, "Resuming HandlerChecker: " + mName + " for reason: "
260 + reason + ". Pause count: " + mPauseCount);
261 } else {
262 Slog.wtf(TAG, "Already resumed HandlerChecker: " + mName);
263 }
264 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800265 }
266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800267 final class RebootRequestReceiver extends BroadcastReceiver {
268 @Override
269 public void onReceive(Context c, Intent intent) {
Dianne Hackbornf6438b12013-05-09 18:53:48 -0700270 if (intent.getIntExtra("nowait", 0) != 0) {
271 rebootSystem("Received ACTION_REBOOT broadcast");
272 return;
273 }
274 Slog.w(TAG, "Unsupported ACTION_REBOOT broadcast: " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800275 }
276 }
277
Wale Ogunwale517daec2015-04-15 10:27:24 -0700278 /** Monitor for checking the availability of binder threads. The monitor will block until
279 * there is a binder thread available to process in coming IPCs to make sure other processes
280 * can still communicate with the service.
281 */
282 private static final class BinderThreadMonitor implements Watchdog.Monitor {
283 @Override
284 public void monitor() {
285 Binder.blockUntilThreadAvailable();
286 }
287 }
288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 public interface Monitor {
290 void monitor();
291 }
292
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 public static Watchdog getInstance() {
294 if (sWatchdog == null) {
295 sWatchdog = new Watchdog();
296 }
297
298 return sWatchdog;
299 }
300
301 private Watchdog() {
302 super("watchdog");
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700303 // Initialize handler checkers for each common thread we want to check. Note
304 // that we are not currently checking the background thread, since it can
305 // potentially hold longer running operations with no guarantees about the timeliness
306 // of operations there.
307
308 // The shared foreground thread is the main checker. It is where we
309 // will also dispatch monitor checks and do other work.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700310 mMonitorChecker = new HandlerChecker(FgThread.getHandler(),
311 "foreground thread", DEFAULT_TIMEOUT);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700312 mHandlerCheckers.add(mMonitorChecker);
313 // Add checker for main thread. We only do a quick check since there
314 // can be UI running on the thread.
315 mHandlerCheckers.add(new HandlerChecker(new Handler(Looper.getMainLooper()),
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700316 "main thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700317 // Add checker for shared UI thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700318 mHandlerCheckers.add(new HandlerChecker(UiThread.getHandler(),
319 "ui thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700320 // And also check IO thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700321 mHandlerCheckers.add(new HandlerChecker(IoThread.getHandler(),
322 "i/o thread", DEFAULT_TIMEOUT));
Jeff Brown4ccb8232014-01-16 22:16:42 -0800323 // And the display thread.
324 mHandlerCheckers.add(new HandlerChecker(DisplayThread.getHandler(),
325 "display thread", DEFAULT_TIMEOUT));
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800326 // And the animation thread.
327 mHandlerCheckers.add(new HandlerChecker(AnimationThread.getHandler(),
328 "animation thread", DEFAULT_TIMEOUT));
329 // And the surface animation thread.
330 mHandlerCheckers.add(new HandlerChecker(SurfaceAnimationThread.getHandler(),
331 "surface animation thread", DEFAULT_TIMEOUT));
Wale Ogunwale517daec2015-04-15 10:27:24 -0700332
333 // Initialize monitor for Binder threads.
334 addMonitor(new BinderThreadMonitor());
Andreas Gampe032a9292017-07-21 11:41:00 -0700335
Narayan Kamatha0a28082017-07-31 15:58:59 +0100336 mOpenFdMonitor = OpenFdMonitor.create();
337
Andreas Gampe032a9292017-07-21 11:41:00 -0700338 // See the notes on DEFAULT_TIMEOUT.
339 assert DB ||
340 DEFAULT_TIMEOUT > ZygoteConnectionConstants.WRAPPED_PID_TIMEOUT_MILLIS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800341 }
342
Zimuzob065b152019-04-16 13:33:01 +0100343 /**
344 * Registers a {@link BroadcastReceiver} to listen to reboot broadcasts and trigger reboot.
345 * Should be called during boot after the ActivityManagerService is up and registered
346 * as a system service so it can handle registration of a {@link BroadcastReceiver}.
347 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800348 public void init(Context context, ActivityManagerService activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 mActivity = activity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800350 context.registerReceiver(new RebootRequestReceiver(),
351 new IntentFilter(Intent.ACTION_REBOOT),
352 android.Manifest.permission.REBOOT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 }
354
Christopher Tatec27181c2010-06-30 14:41:09 -0700355 public void processStarted(String name, int pid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 synchronized (this) {
357 if ("com.android.phone".equals(name)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800358 mPhonePid = pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800359 }
360 }
361 }
362
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700363 public void setActivityController(IActivityController controller) {
364 synchronized (this) {
365 mController = controller;
366 }
367 }
368
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700369 public void setAllowRestart(boolean allowRestart) {
370 synchronized (this) {
371 mAllowRestart = allowRestart;
372 }
373 }
374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800375 public void addMonitor(Monitor monitor) {
376 synchronized (this) {
Makoto Onukie276b442018-08-30 09:38:44 -0700377 mMonitorChecker.addMonitorLocked(monitor);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700378 }
379 }
380
Jeff Brown6f357d32014-01-15 20:40:55 -0800381 public void addThread(Handler thread) {
382 addThread(thread, DEFAULT_TIMEOUT);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700383 }
384
Jeff Brown6f357d32014-01-15 20:40:55 -0800385 public void addThread(Handler thread, long timeoutMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700386 synchronized (this) {
Jeff Brown6f357d32014-01-15 20:40:55 -0800387 final String name = thread.getLooper().getThread().getName();
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700388 mHandlerCheckers.add(new HandlerChecker(thread, name, timeoutMillis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800389 }
390 }
391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392 /**
Zimuzo2a050392019-05-09 12:51:33 +0100393 * Pauses Watchdog action for the currently running thread. Useful before executing long running
394 * operations that could falsely trigger the watchdog. Each call to this will require a matching
395 * call to {@link #resumeWatchingCurrentThread}.
396 *
397 * <p>If the current thread has not been added to the Watchdog, this call is a no-op.
398 *
399 * <p>If the Watchdog is already paused for the current thread, this call adds
400 * adds another pause and will require an additional {@link #resumeCurrentThread} to resume.
401 *
402 * <p>Note: Use with care, as any deadlocks on the current thread will be undetected until all
403 * pauses have been resumed.
404 */
405 public void pauseWatchingCurrentThread(String reason) {
406 synchronized (this) {
407 for (HandlerChecker hc : mHandlerCheckers) {
408 if (Thread.currentThread().equals(hc.getThread())) {
409 hc.pauseLocked(reason);
410 }
411 }
412 }
413 }
414
415 /**
416 * Resumes the last pause from {@link #pauseWatchingCurrentThread} for the currently running
417 * thread.
418 *
419 * <p>If the current thread has not been added to the Watchdog, this call is a no-op.
420 *
421 * <p>If the Watchdog action for the current thread is already resumed, this call logs a wtf.
422 *
423 * <p>If all pauses have been resumed, the Watchdog action is finally resumed, otherwise,
424 * the Watchdog action for the current thread remains paused until resume is called at least
425 * as many times as the calls to pause.
426 */
427 public void resumeWatchingCurrentThread(String reason) {
428 synchronized (this) {
429 for (HandlerChecker hc : mHandlerCheckers) {
430 if (Thread.currentThread().equals(hc.getThread())) {
431 hc.resumeLocked(reason);
432 }
433 }
434 }
435 }
436
437 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 * Perform a full reboot of the system.
439 */
440 void rebootSystem(String reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800441 Slog.i(TAG, "Rebooting system because: " + reason);
Jeff Brown6f357d32014-01-15 20:40:55 -0800442 IPowerManager pms = (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE);
443 try {
444 pms.reboot(false, reason, false);
445 } catch (RemoteException ex) {
446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 }
448
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700449 private int evaluateCheckerCompletionLocked() {
450 int state = COMPLETED;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700451 for (int i=0; i<mHandlerCheckers.size(); i++) {
452 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700453 state = Math.max(state, hc.getCompletionStateLocked());
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700454 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700455 return state;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700456 }
457
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700458 private ArrayList<HandlerChecker> getBlockedCheckersLocked() {
459 ArrayList<HandlerChecker> checkers = new ArrayList<HandlerChecker>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700460 for (int i=0; i<mHandlerCheckers.size(); i++) {
461 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700462 if (hc.isOverdueLocked()) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700463 checkers.add(hc);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700464 }
465 }
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700466 return checkers;
467 }
468
Narayan Kamatha0a28082017-07-31 15:58:59 +0100469 private String describeCheckersLocked(List<HandlerChecker> checkers) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700470 StringBuilder builder = new StringBuilder(128);
471 for (int i=0; i<checkers.size(); i++) {
472 if (builder.length() > 0) {
473 builder.append(", ");
474 }
475 builder.append(checkers.get(i).describeBlockedStateLocked());
476 }
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700477 return builder.toString();
478 }
479
Hui Yu7e65c3f2019-04-16 17:03:16 -0700480 private static ArrayList<Integer> getInterestingHalPids() {
Steven Moreland6b47c542017-03-21 12:52:16 -0700481 try {
482 IServiceManager serviceManager = IServiceManager.getService();
483 ArrayList<IServiceManager.InstanceDebugInfo> dump =
484 serviceManager.debugDump();
485 HashSet<Integer> pids = new HashSet<>();
486 for (IServiceManager.InstanceDebugInfo info : dump) {
487 if (info.pid == IServiceManager.PidConstant.NO_PID) {
488 continue;
489 }
490
491 if (!HAL_INTERFACES_OF_INTEREST.contains(info.interfaceName)) {
492 continue;
493 }
494
495 pids.add(info.pid);
496 }
497 return new ArrayList<Integer>(pids);
498 } catch (RemoteException e) {
499 return new ArrayList<Integer>();
500 }
501 }
502
Hui Yu7e65c3f2019-04-16 17:03:16 -0700503 static ArrayList<Integer> getInterestingNativePids() {
Steven Moreland6b47c542017-03-21 12:52:16 -0700504 ArrayList<Integer> pids = getInterestingHalPids();
505
506 int[] nativePids = Process.getPidsForCommands(NATIVE_STACKS_OF_INTEREST);
507 if (nativePids != null) {
508 pids.ensureCapacity(pids.size() + nativePids.length);
509 for (int i : nativePids) {
510 pids.add(i);
511 }
512 }
513
514 return pids;
515 }
516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800517 @Override
518 public void run() {
Christopher Tate6ee412d2010-05-28 12:01:56 -0700519 boolean waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 while (true) {
Narayan Kamatha0a28082017-07-31 15:58:59 +0100521 final List<HandlerChecker> blockedCheckers;
Jeff Brown7dd2d192013-09-06 15:05:23 -0700522 final String subject;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700523 final boolean allowRestart;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700524 int debuggerWasConnected = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800525 synchronized (this) {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700526 long timeout = CHECK_INTERVAL;
527 // Make sure we (re)spin the checkers that have become idle within
528 // this wait-and-check interval
529 for (int i=0; i<mHandlerCheckers.size(); i++) {
530 HandlerChecker hc = mHandlerCheckers.get(i);
531 hc.scheduleCheckLocked();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700532 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700534 if (debuggerWasConnected > 0) {
535 debuggerWasConnected--;
536 }
537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800538 // NOTE: We use uptimeMillis() here because we do not want to increment the time we
539 // wait while asleep. If the device is asleep then the thing that we are waiting
Christopher Tate6ee412d2010-05-28 12:01:56 -0700540 // 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 -0800541 // positive on when to kill things.
542 long start = SystemClock.uptimeMillis();
Michael Wright8fa56f62013-04-01 16:36:05 -0700543 while (timeout > 0) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700544 if (Debug.isDebuggerConnected()) {
545 debuggerWasConnected = 2;
546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 try {
Michael Wright8fa56f62013-04-01 16:36:05 -0700548 wait(timeout);
Zimuzob065b152019-04-16 13:33:01 +0100549 // Note: mHandlerCheckers and mMonitorChecker may have changed after waiting
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 } catch (InterruptedException e) {
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800551 Log.wtf(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700553 if (Debug.isDebuggerConnected()) {
554 debuggerWasConnected = 2;
555 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700556 timeout = CHECK_INTERVAL - (SystemClock.uptimeMillis() - start);
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558
Narayan Kamatha0a28082017-07-31 15:58:59 +0100559 boolean fdLimitTriggered = false;
560 if (mOpenFdMonitor != null) {
561 fdLimitTriggered = mOpenFdMonitor.monitor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 }
Michael Wright8fa56f62013-04-01 16:36:05 -0700563
Narayan Kamatha0a28082017-07-31 15:58:59 +0100564 if (!fdLimitTriggered) {
565 final int waitState = evaluateCheckerCompletionLocked();
566 if (waitState == COMPLETED) {
567 // The monitors have returned; reset
568 waitedHalf = false;
569 continue;
570 } else if (waitState == WAITING) {
571 // still waiting but within their configured intervals; back off and recheck
572 continue;
573 } else if (waitState == WAITED_HALF) {
574 if (!waitedHalf) {
Makoto Onuki729c41e2019-05-30 09:47:10 -0700575 Slog.i(TAG, "WAITED_HALF");
Narayan Kamatha0a28082017-07-31 15:58:59 +0100576 // We've waited half the deadlock-detection interval. Pull a stack
577 // trace and wait another half.
578 ArrayList<Integer> pids = new ArrayList<Integer>();
579 pids.add(Process.myPid());
Makoto Onukie276b442018-08-30 09:38:44 -0700580 ActivityManagerService.dumpStackTraces(pids, null, null,
Narayan Kamatha0a28082017-07-31 15:58:59 +0100581 getInterestingNativePids());
582 waitedHalf = true;
583 }
584 continue;
585 }
586
587 // something is overdue!
588 blockedCheckers = getBlockedCheckersLocked();
589 subject = describeCheckersLocked(blockedCheckers);
590 } else {
591 blockedCheckers = Collections.emptyList();
592 subject = "Open FD high water mark reached";
593 }
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700594 allowRestart = mAllowRestart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 }
596
597 // If we got here, that means that the system is most likely hung.
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700598 // First collect stack traces from all threads of the system process.
599 // Then kill this process so that the system will restart.
Jeff Brown7dd2d192013-09-06 15:05:23 -0700600 EventLog.writeEvent(EventLogTags.WATCHDOG, subject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601
Steven Moreland6b47c542017-03-21 12:52:16 -0700602 ArrayList<Integer> pids = new ArrayList<>();
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800603 pids.add(Process.myPid());
Dan Egnor4bded072010-03-11 22:00:47 -0800604 if (mPhonePid > 0) pids.add(mPhonePid);
Makoto Onukie276b442018-08-30 09:38:44 -0700605
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800606 final File stack = ActivityManagerService.dumpStackTraces(
Makoto Onukie276b442018-08-30 09:38:44 -0700607 pids, null, null, getInterestingNativePids());
Dan Egnor4bded072010-03-11 22:00:47 -0800608
609 // Give some extra time to make sure the stack traces get written.
610 // The system's been hanging for a minute, another second or two won't hurt much.
Makoto Onukie276b442018-08-30 09:38:44 -0700611 SystemClock.sleep(5000);
Dan Egnor4bded072010-03-11 22:00:47 -0800612
Guang Zhu0620c452014-10-29 14:31:48 -0700613 // Trigger the kernel to dump all blocked threads, and backtraces on all CPUs to the kernel log
614 doSysRq('w');
615 doSysRq('l');
Colin Cross5df1d872012-11-29 11:42:11 -0800616
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800617 // Try to add the error to the dropbox, but assuming that the ActivityManager
618 // itself may be deadlocked. (which has happened, causing this statement to
619 // deadlock and the watchdog as a whole to be ineffective)
620 Thread dropboxThread = new Thread("watchdogWriteToDropbox") {
621 public void run() {
Amith Yamasanifa7c36892019-05-15 17:32:27 -0700622 // If a watched thread hangs before init() is called, we don't have a
623 // valid mActivity. So we can't log the error to dropbox.
624 if (mActivity != null) {
625 mActivity.addErrorToDropBox(
626 "watchdog", null, "system_server", null, null, null,
627 subject, null, stack, null);
628 }
jianjin8f2dee02019-03-29 14:03:08 -0700629 StatsLog.write(StatsLog.SYSTEM_SERVER_WATCHDOG_OCCURRED, subject);
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800630 }
631 };
632 dropboxThread.start();
633 try {
634 dropboxThread.join(2000); // wait up to 2 seconds for it to return.
635 } catch (InterruptedException ignored) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800636
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700637 IActivityController controller;
638 synchronized (this) {
639 controller = mController;
640 }
641 if (controller != null) {
642 Slog.i(TAG, "Reporting stuck state to activity controller");
643 try {
644 Binder.setDumpDisabled("Service dumps disabled due to hung system process.");
645 // 1 = keep waiting, -1 = kill system
Jeff Brown7dd2d192013-09-06 15:05:23 -0700646 int res = controller.systemNotResponding(subject);
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700647 if (res >= 0) {
648 Slog.i(TAG, "Activity controller requested to coninue to wait");
649 waitedHalf = false;
650 continue;
651 }
652 } catch (RemoteException e) {
653 }
654 }
655
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700656 // Only kill the process if the debugger is not attached.
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700657 if (Debug.isDebuggerConnected()) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700658 debuggerWasConnected = 2;
659 }
660 if (debuggerWasConnected >= 2) {
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700661 Slog.w(TAG, "Debugger connected: Watchdog is *not* killing the system process");
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700662 } else if (debuggerWasConnected > 0) {
663 Slog.w(TAG, "Debugger was connected: Watchdog is *not* killing the system process");
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700664 } else if (!allowRestart) {
665 Slog.w(TAG, "Restart not allowed: Watchdog is *not* killing the system process");
666 } else {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700667 Slog.w(TAG, "*** WATCHDOG KILLING SYSTEM PROCESS: " + subject);
Andreas Gampe544416e2018-01-26 11:39:46 -0800668 WatchdogDiagnostics.diagnoseCheckers(blockedCheckers);
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700669 Slog.w(TAG, "*** GOODBYE!");
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700670 Process.killProcess(Process.myPid());
671 System.exit(10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800672 }
Christopher Tate6ee412d2010-05-28 12:01:56 -0700673
674 waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800675 }
676 }
Christopher Tateecaa7b42010-06-04 14:55:02 -0700677
Guang Zhu0620c452014-10-29 14:31:48 -0700678 private void doSysRq(char c) {
679 try {
680 FileWriter sysrq_trigger = new FileWriter("/proc/sysrq-trigger");
681 sysrq_trigger.write(c);
682 sysrq_trigger.close();
683 } catch (IOException e) {
684 Slog.w(TAG, "Failed to write to /proc/sysrq-trigger", e);
685 }
686 }
687
Narayan Kamatha0a28082017-07-31 15:58:59 +0100688 public static final class OpenFdMonitor {
689 /**
690 * Number of FDs below the soft limit that we trigger a runtime restart at. This was
691 * chosen arbitrarily, but will need to be at least 6 in order to have a sufficient number
692 * of FDs in reserve to complete a dump.
693 */
694 private static final int FD_HIGH_WATER_MARK = 12;
695
696 private final File mDumpDir;
697 private final File mFdHighWaterMark;
698
699 public static OpenFdMonitor create() {
700 // Only run the FD monitor on debuggable builds (such as userdebug and eng builds).
701 if (!Build.IS_DEBUGGABLE) {
702 return null;
703 }
704
Narayan Kamatha0a28082017-07-31 15:58:59 +0100705 final StructRlimit rlimit;
706 try {
707 rlimit = android.system.Os.getrlimit(OsConstants.RLIMIT_NOFILE);
708 } catch (ErrnoException errno) {
709 Slog.w(TAG, "Error thrown from getrlimit(RLIMIT_NOFILE)", errno);
710 return null;
711 }
712
713 // The assumption we're making here is that FD numbers are allocated (more or less)
714 // sequentially, which is currently (and historically) true since open is currently
715 // specified to always return the lowest-numbered non-open file descriptor for the
716 // current process.
717 //
718 // We do this to avoid having to enumerate the contents of /proc/self/fd in order to
719 // count the number of descriptors open in the process.
720 final File fdThreshold = new File("/proc/self/fd/" + (rlimit.rlim_cur - FD_HIGH_WATER_MARK));
Elliott Hughes4e4caa72018-03-23 11:06:36 -0700721 return new OpenFdMonitor(new File("/data/anr"), fdThreshold);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100722 }
723
724 OpenFdMonitor(File dumpDir, File fdThreshold) {
725 mDumpDir = dumpDir;
726 mFdHighWaterMark = fdThreshold;
727 }
728
Nandana Dutt6647ef52018-07-12 17:02:57 +0100729 /**
730 * Dumps open file descriptors and their full paths to a temporary file in {@code mDumpDir}.
731 */
Narayan Kamatha0a28082017-07-31 15:58:59 +0100732 private void dumpOpenDescriptors() {
Nandana Dutt6647ef52018-07-12 17:02:57 +0100733 // We cannot exec lsof to get more info about open file descriptors because a newly
734 // forked process will not have the permissions to readlink. Instead list all open
735 // descriptors from /proc/pid/fd and resolve them.
736 List<String> dumpInfo = new ArrayList<>();
737 String fdDirPath = String.format("/proc/%d/fd/", Process.myPid());
738 File[] fds = new File(fdDirPath).listFiles();
739 if (fds == null) {
740 dumpInfo.add("Unable to list " + fdDirPath);
741 } else {
742 for (File f : fds) {
743 String fdSymLink = f.getAbsolutePath();
744 String resolvedPath = "";
745 try {
746 resolvedPath = Os.readlink(fdSymLink);
747 } catch (ErrnoException ex) {
748 resolvedPath = ex.getMessage();
749 }
750 dumpInfo.add(fdSymLink + "\t" + resolvedPath);
751 }
752 }
753
754 // Dump the fds & paths to a temp file.
Narayan Kamatha0a28082017-07-31 15:58:59 +0100755 try {
756 File dumpFile = File.createTempFile("anr_fd_", "", mDumpDir);
Nandana Dutt6647ef52018-07-12 17:02:57 +0100757 Path out = Paths.get(dumpFile.getAbsolutePath());
758 Files.write(out, dumpInfo, StandardCharsets.UTF_8);
759 } catch (IOException ex) {
760 Slog.w(TAG, "Unable to write open descriptors to file: " + ex);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100761 }
762 }
763
764 /**
765 * @return {@code true} if the high water mark was breached and a dump was written,
766 * {@code false} otherwise.
767 */
768 public boolean monitor() {
769 if (mFdHighWaterMark.exists()) {
770 dumpOpenDescriptors();
771 return true;
772 }
773
774 return false;
775 }
776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777}