blob: 1aeb6898fa13b7f031cfc92af23558424164f760 [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;
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. */
66 public static final boolean DEBUG = true; // STOPSHIP disable it (b/113252928)
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
Andreas Gampecf9e79b2016-05-11 18:41:25 -070098 "com.android.bluetooth", // Bluetooth service
Rafal Slawike35d8f82018-10-01 11:39:58 +010099 "/system/bin/statsd", // Stats daemon
Dianne Hackbornf72467a2012-06-08 17:23:59 -0700100 };
101
Steven Moreland6b47c542017-03-21 12:52:16 -0700102 public static final List<String> HAL_INTERFACES_OF_INTEREST = Arrays.asList(
103 "android.hardware.audio@2.0::IDevicesFactory",
Mikhail Naganov09f0c5a2018-04-30 15:58:31 -0700104 "android.hardware.audio@4.0::IDevicesFactory",
Steven Moreland6b47c542017-03-21 12:52:16 -0700105 "android.hardware.bluetooth@1.0::IBluetoothHci",
106 "android.hardware.camera.provider@2.4::ICameraProvider",
Chia-I Wu49569e32018-08-01 09:59:02 -0700107 "android.hardware.graphics.allocator@2.0::IAllocator",
Chia-I Wu74debcd2017-04-21 11:14:22 -0700108 "android.hardware.graphics.composer@2.1::IComposer",
Yifan Honge8ea5222018-11-27 16:42:13 -0800109 "android.hardware.health@2.0::IHealth",
Peng Xu102122fb2017-07-11 21:12:11 -0700110 "android.hardware.media.omx@1.0::IOmx",
Pawin Vongmasaf22f5f72018-04-18 07:01:47 -0700111 "android.hardware.media.omx@1.0::IOmxStore",
Peng Xu102122fb2017-07-11 21:12:11 -0700112 "android.hardware.sensors@1.0::ISensors",
113 "android.hardware.vr@1.0::IVr"
Steven Moreland6b47c542017-03-21 12:52:16 -0700114 );
115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 static Watchdog sWatchdog;
117
118 /* This handler will be used to post message back onto the main thread */
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700119 final ArrayList<HandlerChecker> mHandlerCheckers = new ArrayList<>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700120 final HandlerChecker mMonitorChecker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 ContentResolver mResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 ActivityManagerService mActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124 int mPhonePid;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700125 IActivityController mController;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700126 boolean mAllowRestart = true;
Narayan Kamatha0a28082017-07-31 15:58:59 +0100127 final OpenFdMonitor mOpenFdMonitor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129 /**
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700130 * Used for checking status of handle threads and scheduling monitor callbacks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700132 public final class HandlerChecker implements Runnable {
133 private final Handler mHandler;
134 private final String mName;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700135 private final long mWaitMax;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700136 private final ArrayList<Monitor> mMonitors = new ArrayList<Monitor>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700137 private boolean mCompleted;
138 private Monitor mCurrentMonitor;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700139 private long mStartTime;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700140
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700141 HandlerChecker(Handler handler, String name, long waitMaxMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700142 mHandler = handler;
143 mName = name;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700144 mWaitMax = waitMaxMillis;
145 mCompleted = true;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700146 }
147
Makoto Onukie276b442018-08-30 09:38:44 -0700148 void addMonitorLocked(Monitor monitor) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700149 mMonitors.add(monitor);
150 }
151
152 public void scheduleCheckLocked() {
Jeff Brown6c7b41a2015-02-26 14:43:53 -0800153 if (mMonitors.size() == 0 && mHandler.getLooper().getQueue().isPolling()) {
154 // If the target looper has recently been polling, then
Dianne Hackbornefa92b22013-05-03 14:11:43 -0700155 // there is no reason to enqueue our checker on it since that
156 // is as good as it not being deadlocked. This avoid having
157 // to do a context switch to check the thread. Note that we
158 // only do this if mCheckReboot is false and we have no
159 // monitors, since those would need to be executed at this point.
160 mCompleted = true;
161 return;
162 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700163
164 if (!mCompleted) {
165 // we already have a check in flight, so no need
166 return;
167 }
168
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700169 mCompleted = false;
170 mCurrentMonitor = null;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700171 mStartTime = SystemClock.uptimeMillis();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700172 mHandler.postAtFrontOfQueue(this);
173 }
174
Makoto Onukie276b442018-08-30 09:38:44 -0700175 boolean isOverdueLocked() {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700176 return (!mCompleted) && (SystemClock.uptimeMillis() > mStartTime + mWaitMax);
177 }
178
179 public int getCompletionStateLocked() {
180 if (mCompleted) {
181 return COMPLETED;
182 } else {
183 long latency = SystemClock.uptimeMillis() - mStartTime;
184 if (latency < mWaitMax/2) {
185 return WAITING;
186 } else if (latency < mWaitMax) {
187 return WAITED_HALF;
188 }
189 }
190 return OVERDUE;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700191 }
192
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700193 public Thread getThread() {
194 return mHandler.getLooper().getThread();
195 }
196
197 public String getName() {
198 return mName;
199 }
200
Makoto Onukie276b442018-08-30 09:38:44 -0700201 String describeBlockedStateLocked() {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700202 if (mCurrentMonitor == null) {
203 return "Blocked in handler on " + mName + " (" + getThread().getName() + ")";
204 } else {
205 return "Blocked in monitor " + mCurrentMonitor.getClass().getName()
206 + " on " + mName + " (" + getThread().getName() + ")";
207 }
John Michelau11641522013-03-18 18:28:23 -0500208 }
209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210 @Override
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700211 public void run() {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700212 final int size = mMonitors.size();
213 for (int i = 0 ; i < size ; i++) {
214 synchronized (Watchdog.this) {
215 mCurrentMonitor = mMonitors.get(i);
216 }
217 mCurrentMonitor.monitor();
218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700220 synchronized (Watchdog.this) {
221 mCompleted = true;
222 mCurrentMonitor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223 }
224 }
225 }
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 final class RebootRequestReceiver extends BroadcastReceiver {
228 @Override
229 public void onReceive(Context c, Intent intent) {
Dianne Hackbornf6438b12013-05-09 18:53:48 -0700230 if (intent.getIntExtra("nowait", 0) != 0) {
231 rebootSystem("Received ACTION_REBOOT broadcast");
232 return;
233 }
234 Slog.w(TAG, "Unsupported ACTION_REBOOT broadcast: " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235 }
236 }
237
Wale Ogunwale517daec2015-04-15 10:27:24 -0700238 /** Monitor for checking the availability of binder threads. The monitor will block until
239 * there is a binder thread available to process in coming IPCs to make sure other processes
240 * can still communicate with the service.
241 */
242 private static final class BinderThreadMonitor implements Watchdog.Monitor {
243 @Override
244 public void monitor() {
245 Binder.blockUntilThreadAvailable();
246 }
247 }
248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800249 public interface Monitor {
250 void monitor();
251 }
252
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800253 public static Watchdog getInstance() {
254 if (sWatchdog == null) {
255 sWatchdog = new Watchdog();
256 }
257
258 return sWatchdog;
259 }
260
261 private Watchdog() {
262 super("watchdog");
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700263 // Initialize handler checkers for each common thread we want to check. Note
264 // that we are not currently checking the background thread, since it can
265 // potentially hold longer running operations with no guarantees about the timeliness
266 // of operations there.
267
268 // The shared foreground thread is the main checker. It is where we
269 // will also dispatch monitor checks and do other work.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700270 mMonitorChecker = new HandlerChecker(FgThread.getHandler(),
271 "foreground thread", DEFAULT_TIMEOUT);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700272 mHandlerCheckers.add(mMonitorChecker);
273 // Add checker for main thread. We only do a quick check since there
274 // can be UI running on the thread.
275 mHandlerCheckers.add(new HandlerChecker(new Handler(Looper.getMainLooper()),
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700276 "main thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700277 // Add checker for shared UI thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700278 mHandlerCheckers.add(new HandlerChecker(UiThread.getHandler(),
279 "ui thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700280 // And also check IO thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700281 mHandlerCheckers.add(new HandlerChecker(IoThread.getHandler(),
282 "i/o thread", DEFAULT_TIMEOUT));
Jeff Brown4ccb8232014-01-16 22:16:42 -0800283 // And the display thread.
284 mHandlerCheckers.add(new HandlerChecker(DisplayThread.getHandler(),
285 "display thread", DEFAULT_TIMEOUT));
Wale Ogunwale1f5e53d2018-11-05 05:12:46 -0800286 // And the animation thread.
287 mHandlerCheckers.add(new HandlerChecker(AnimationThread.getHandler(),
288 "animation thread", DEFAULT_TIMEOUT));
289 // And the surface animation thread.
290 mHandlerCheckers.add(new HandlerChecker(SurfaceAnimationThread.getHandler(),
291 "surface animation thread", DEFAULT_TIMEOUT));
Wale Ogunwale517daec2015-04-15 10:27:24 -0700292
293 // Initialize monitor for Binder threads.
294 addMonitor(new BinderThreadMonitor());
Andreas Gampe032a9292017-07-21 11:41:00 -0700295
Narayan Kamatha0a28082017-07-31 15:58:59 +0100296 mOpenFdMonitor = OpenFdMonitor.create();
297
Andreas Gampe032a9292017-07-21 11:41:00 -0700298 // See the notes on DEFAULT_TIMEOUT.
299 assert DB ||
300 DEFAULT_TIMEOUT > ZygoteConnectionConstants.WRAPPED_PID_TIMEOUT_MILLIS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 }
302
Adam Lesinski182f73f2013-12-05 16:48:06 -0800303 public void init(Context context, ActivityManagerService activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 mResolver = context.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800305 mActivity = activity;
306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 context.registerReceiver(new RebootRequestReceiver(),
308 new IntentFilter(Intent.ACTION_REBOOT),
309 android.Manifest.permission.REBOOT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800310 }
311
Christopher Tatec27181c2010-06-30 14:41:09 -0700312 public void processStarted(String name, int pid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800313 synchronized (this) {
314 if ("com.android.phone".equals(name)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800315 mPhonePid = pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 }
317 }
318 }
319
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700320 public void setActivityController(IActivityController controller) {
321 synchronized (this) {
322 mController = controller;
323 }
324 }
325
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700326 public void setAllowRestart(boolean allowRestart) {
327 synchronized (this) {
328 mAllowRestart = allowRestart;
329 }
330 }
331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800332 public void addMonitor(Monitor monitor) {
333 synchronized (this) {
334 if (isAlive()) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700335 throw new RuntimeException("Monitors can't be added once the Watchdog is running");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 }
Makoto Onukie276b442018-08-30 09:38:44 -0700337 mMonitorChecker.addMonitorLocked(monitor);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700338 }
339 }
340
Jeff Brown6f357d32014-01-15 20:40:55 -0800341 public void addThread(Handler thread) {
342 addThread(thread, DEFAULT_TIMEOUT);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700343 }
344
Jeff Brown6f357d32014-01-15 20:40:55 -0800345 public void addThread(Handler thread, long timeoutMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700346 synchronized (this) {
347 if (isAlive()) {
348 throw new RuntimeException("Threads can't be added once the Watchdog is running");
349 }
Jeff Brown6f357d32014-01-15 20:40:55 -0800350 final String name = thread.getLooper().getThread().getName();
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700351 mHandlerCheckers.add(new HandlerChecker(thread, name, timeoutMillis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800352 }
353 }
354
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800355 /**
356 * Perform a full reboot of the system.
357 */
358 void rebootSystem(String reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800359 Slog.i(TAG, "Rebooting system because: " + reason);
Jeff Brown6f357d32014-01-15 20:40:55 -0800360 IPowerManager pms = (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE);
361 try {
362 pms.reboot(false, reason, false);
363 } catch (RemoteException ex) {
364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800365 }
366
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700367 private int evaluateCheckerCompletionLocked() {
368 int state = COMPLETED;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700369 for (int i=0; i<mHandlerCheckers.size(); i++) {
370 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700371 state = Math.max(state, hc.getCompletionStateLocked());
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700372 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700373 return state;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700374 }
375
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700376 private ArrayList<HandlerChecker> getBlockedCheckersLocked() {
377 ArrayList<HandlerChecker> checkers = new ArrayList<HandlerChecker>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700378 for (int i=0; i<mHandlerCheckers.size(); i++) {
379 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700380 if (hc.isOverdueLocked()) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700381 checkers.add(hc);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700382 }
383 }
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700384 return checkers;
385 }
386
Narayan Kamatha0a28082017-07-31 15:58:59 +0100387 private String describeCheckersLocked(List<HandlerChecker> checkers) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700388 StringBuilder builder = new StringBuilder(128);
389 for (int i=0; i<checkers.size(); i++) {
390 if (builder.length() > 0) {
391 builder.append(", ");
392 }
393 builder.append(checkers.get(i).describeBlockedStateLocked());
394 }
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700395 return builder.toString();
396 }
397
Steven Moreland6b47c542017-03-21 12:52:16 -0700398 private ArrayList<Integer> getInterestingHalPids() {
399 try {
400 IServiceManager serviceManager = IServiceManager.getService();
401 ArrayList<IServiceManager.InstanceDebugInfo> dump =
402 serviceManager.debugDump();
403 HashSet<Integer> pids = new HashSet<>();
404 for (IServiceManager.InstanceDebugInfo info : dump) {
405 if (info.pid == IServiceManager.PidConstant.NO_PID) {
406 continue;
407 }
408
409 if (!HAL_INTERFACES_OF_INTEREST.contains(info.interfaceName)) {
410 continue;
411 }
412
413 pids.add(info.pid);
414 }
415 return new ArrayList<Integer>(pids);
416 } catch (RemoteException e) {
417 return new ArrayList<Integer>();
418 }
419 }
420
421 private ArrayList<Integer> getInterestingNativePids() {
422 ArrayList<Integer> pids = getInterestingHalPids();
423
424 int[] nativePids = Process.getPidsForCommands(NATIVE_STACKS_OF_INTEREST);
425 if (nativePids != null) {
426 pids.ensureCapacity(pids.size() + nativePids.length);
427 for (int i : nativePids) {
428 pids.add(i);
429 }
430 }
431
432 return pids;
433 }
434
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435 @Override
436 public void run() {
Christopher Tate6ee412d2010-05-28 12:01:56 -0700437 boolean waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800438 while (true) {
Narayan Kamatha0a28082017-07-31 15:58:59 +0100439 final List<HandlerChecker> blockedCheckers;
Jeff Brown7dd2d192013-09-06 15:05:23 -0700440 final String subject;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700441 final boolean allowRestart;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700442 int debuggerWasConnected = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800443 synchronized (this) {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700444 long timeout = CHECK_INTERVAL;
445 // Make sure we (re)spin the checkers that have become idle within
446 // this wait-and-check interval
447 for (int i=0; i<mHandlerCheckers.size(); i++) {
448 HandlerChecker hc = mHandlerCheckers.get(i);
449 hc.scheduleCheckLocked();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700450 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700452 if (debuggerWasConnected > 0) {
453 debuggerWasConnected--;
454 }
455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 // NOTE: We use uptimeMillis() here because we do not want to increment the time we
457 // wait while asleep. If the device is asleep then the thing that we are waiting
Christopher Tate6ee412d2010-05-28 12:01:56 -0700458 // 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 -0800459 // positive on when to kill things.
460 long start = SystemClock.uptimeMillis();
Michael Wright8fa56f62013-04-01 16:36:05 -0700461 while (timeout > 0) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700462 if (Debug.isDebuggerConnected()) {
463 debuggerWasConnected = 2;
464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465 try {
Michael Wright8fa56f62013-04-01 16:36:05 -0700466 wait(timeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 } catch (InterruptedException e) {
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800468 Log.wtf(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700470 if (Debug.isDebuggerConnected()) {
471 debuggerWasConnected = 2;
472 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700473 timeout = CHECK_INTERVAL - (SystemClock.uptimeMillis() - start);
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475
Narayan Kamatha0a28082017-07-31 15:58:59 +0100476 boolean fdLimitTriggered = false;
477 if (mOpenFdMonitor != null) {
478 fdLimitTriggered = mOpenFdMonitor.monitor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800479 }
Michael Wright8fa56f62013-04-01 16:36:05 -0700480
Narayan Kamatha0a28082017-07-31 15:58:59 +0100481 if (!fdLimitTriggered) {
482 final int waitState = evaluateCheckerCompletionLocked();
483 if (waitState == COMPLETED) {
484 // The monitors have returned; reset
485 waitedHalf = false;
486 continue;
487 } else if (waitState == WAITING) {
488 // still waiting but within their configured intervals; back off and recheck
489 continue;
490 } else if (waitState == WAITED_HALF) {
491 if (!waitedHalf) {
Makoto Onuki99029542018-08-27 17:23:09 -0700492 if (DEBUG) Slog.d(TAG, "WAITED_HALF");
Narayan Kamatha0a28082017-07-31 15:58:59 +0100493 // We've waited half the deadlock-detection interval. Pull a stack
494 // trace and wait another half.
495 ArrayList<Integer> pids = new ArrayList<Integer>();
496 pids.add(Process.myPid());
Makoto Onukie276b442018-08-30 09:38:44 -0700497 ActivityManagerService.dumpStackTraces(pids, null, null,
Narayan Kamatha0a28082017-07-31 15:58:59 +0100498 getInterestingNativePids());
499 waitedHalf = true;
500 }
501 continue;
502 }
503
504 // something is overdue!
505 blockedCheckers = getBlockedCheckersLocked();
506 subject = describeCheckersLocked(blockedCheckers);
507 } else {
508 blockedCheckers = Collections.emptyList();
509 subject = "Open FD high water mark reached";
510 }
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700511 allowRestart = mAllowRestart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800512 }
513
514 // If we got here, that means that the system is most likely hung.
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700515 // First collect stack traces from all threads of the system process.
516 // Then kill this process so that the system will restart.
Jeff Brown7dd2d192013-09-06 15:05:23 -0700517 EventLog.writeEvent(EventLogTags.WATCHDOG, subject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800518
Steven Moreland6b47c542017-03-21 12:52:16 -0700519 ArrayList<Integer> pids = new ArrayList<>();
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800520 pids.add(Process.myPid());
Dan Egnor4bded072010-03-11 22:00:47 -0800521 if (mPhonePid > 0) pids.add(mPhonePid);
Makoto Onukie276b442018-08-30 09:38:44 -0700522
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800523 final File stack = ActivityManagerService.dumpStackTraces(
Makoto Onukie276b442018-08-30 09:38:44 -0700524 pids, null, null, getInterestingNativePids());
Dan Egnor4bded072010-03-11 22:00:47 -0800525
526 // Give some extra time to make sure the stack traces get written.
527 // The system's been hanging for a minute, another second or two won't hurt much.
Makoto Onukie276b442018-08-30 09:38:44 -0700528 SystemClock.sleep(5000);
Dan Egnor4bded072010-03-11 22:00:47 -0800529
Guang Zhu0620c452014-10-29 14:31:48 -0700530 // Trigger the kernel to dump all blocked threads, and backtraces on all CPUs to the kernel log
531 doSysRq('w');
532 doSysRq('l');
Colin Cross5df1d872012-11-29 11:42:11 -0800533
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800534 // Try to add the error to the dropbox, but assuming that the ActivityManager
535 // itself may be deadlocked. (which has happened, causing this statement to
536 // deadlock and the watchdog as a whole to be ineffective)
537 Thread dropboxThread = new Thread("watchdogWriteToDropbox") {
538 public void run() {
539 mActivity.addErrorToDropBox(
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700540 "watchdog", null, "system_server", null, null, null,
Jeff Brown7dd2d192013-09-06 15:05:23 -0700541 subject, null, stack, null);
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800542 }
543 };
544 dropboxThread.start();
545 try {
546 dropboxThread.join(2000); // wait up to 2 seconds for it to return.
547 } catch (InterruptedException ignored) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800548
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700549 IActivityController controller;
550 synchronized (this) {
551 controller = mController;
552 }
553 if (controller != null) {
554 Slog.i(TAG, "Reporting stuck state to activity controller");
555 try {
556 Binder.setDumpDisabled("Service dumps disabled due to hung system process.");
557 // 1 = keep waiting, -1 = kill system
Jeff Brown7dd2d192013-09-06 15:05:23 -0700558 int res = controller.systemNotResponding(subject);
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700559 if (res >= 0) {
560 Slog.i(TAG, "Activity controller requested to coninue to wait");
561 waitedHalf = false;
562 continue;
563 }
564 } catch (RemoteException e) {
565 }
566 }
567
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700568 // Only kill the process if the debugger is not attached.
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700569 if (Debug.isDebuggerConnected()) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700570 debuggerWasConnected = 2;
571 }
572 if (debuggerWasConnected >= 2) {
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700573 Slog.w(TAG, "Debugger connected: Watchdog is *not* killing the system process");
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700574 } else if (debuggerWasConnected > 0) {
575 Slog.w(TAG, "Debugger was connected: Watchdog is *not* killing the system process");
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700576 } else if (!allowRestart) {
577 Slog.w(TAG, "Restart not allowed: Watchdog is *not* killing the system process");
578 } else {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700579 Slog.w(TAG, "*** WATCHDOG KILLING SYSTEM PROCESS: " + subject);
Andreas Gampe544416e2018-01-26 11:39:46 -0800580 WatchdogDiagnostics.diagnoseCheckers(blockedCheckers);
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700581 Slog.w(TAG, "*** GOODBYE!");
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700582 Process.killProcess(Process.myPid());
583 System.exit(10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 }
Christopher Tate6ee412d2010-05-28 12:01:56 -0700585
586 waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800587 }
588 }
Christopher Tateecaa7b42010-06-04 14:55:02 -0700589
Guang Zhu0620c452014-10-29 14:31:48 -0700590 private void doSysRq(char c) {
591 try {
592 FileWriter sysrq_trigger = new FileWriter("/proc/sysrq-trigger");
593 sysrq_trigger.write(c);
594 sysrq_trigger.close();
595 } catch (IOException e) {
596 Slog.w(TAG, "Failed to write to /proc/sysrq-trigger", e);
597 }
598 }
599
Narayan Kamatha0a28082017-07-31 15:58:59 +0100600 public static final class OpenFdMonitor {
601 /**
602 * Number of FDs below the soft limit that we trigger a runtime restart at. This was
603 * chosen arbitrarily, but will need to be at least 6 in order to have a sufficient number
604 * of FDs in reserve to complete a dump.
605 */
606 private static final int FD_HIGH_WATER_MARK = 12;
607
608 private final File mDumpDir;
609 private final File mFdHighWaterMark;
610
611 public static OpenFdMonitor create() {
612 // Only run the FD monitor on debuggable builds (such as userdebug and eng builds).
613 if (!Build.IS_DEBUGGABLE) {
614 return null;
615 }
616
Narayan Kamatha0a28082017-07-31 15:58:59 +0100617 final StructRlimit rlimit;
618 try {
619 rlimit = android.system.Os.getrlimit(OsConstants.RLIMIT_NOFILE);
620 } catch (ErrnoException errno) {
621 Slog.w(TAG, "Error thrown from getrlimit(RLIMIT_NOFILE)", errno);
622 return null;
623 }
624
625 // The assumption we're making here is that FD numbers are allocated (more or less)
626 // sequentially, which is currently (and historically) true since open is currently
627 // specified to always return the lowest-numbered non-open file descriptor for the
628 // current process.
629 //
630 // We do this to avoid having to enumerate the contents of /proc/self/fd in order to
631 // count the number of descriptors open in the process.
632 final File fdThreshold = new File("/proc/self/fd/" + (rlimit.rlim_cur - FD_HIGH_WATER_MARK));
Elliott Hughes4e4caa72018-03-23 11:06:36 -0700633 return new OpenFdMonitor(new File("/data/anr"), fdThreshold);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100634 }
635
636 OpenFdMonitor(File dumpDir, File fdThreshold) {
637 mDumpDir = dumpDir;
638 mFdHighWaterMark = fdThreshold;
639 }
640
Nandana Dutt6647ef52018-07-12 17:02:57 +0100641 /**
642 * Dumps open file descriptors and their full paths to a temporary file in {@code mDumpDir}.
643 */
Narayan Kamatha0a28082017-07-31 15:58:59 +0100644 private void dumpOpenDescriptors() {
Nandana Dutt6647ef52018-07-12 17:02:57 +0100645 // We cannot exec lsof to get more info about open file descriptors because a newly
646 // forked process will not have the permissions to readlink. Instead list all open
647 // descriptors from /proc/pid/fd and resolve them.
648 List<String> dumpInfo = new ArrayList<>();
649 String fdDirPath = String.format("/proc/%d/fd/", Process.myPid());
650 File[] fds = new File(fdDirPath).listFiles();
651 if (fds == null) {
652 dumpInfo.add("Unable to list " + fdDirPath);
653 } else {
654 for (File f : fds) {
655 String fdSymLink = f.getAbsolutePath();
656 String resolvedPath = "";
657 try {
658 resolvedPath = Os.readlink(fdSymLink);
659 } catch (ErrnoException ex) {
660 resolvedPath = ex.getMessage();
661 }
662 dumpInfo.add(fdSymLink + "\t" + resolvedPath);
663 }
664 }
665
666 // Dump the fds & paths to a temp file.
Narayan Kamatha0a28082017-07-31 15:58:59 +0100667 try {
668 File dumpFile = File.createTempFile("anr_fd_", "", mDumpDir);
Nandana Dutt6647ef52018-07-12 17:02:57 +0100669 Path out = Paths.get(dumpFile.getAbsolutePath());
670 Files.write(out, dumpInfo, StandardCharsets.UTF_8);
671 } catch (IOException ex) {
672 Slog.w(TAG, "Unable to write open descriptors to file: " + ex);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100673 }
674 }
675
676 /**
677 * @return {@code true} if the high water mark was breached and a dump was written,
678 * {@code false} otherwise.
679 */
680 public boolean monitor() {
681 if (mFdHighWaterMark.exists()) {
682 dumpOpenDescriptors();
683 return true;
684 }
685
686 return false;
687 }
688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800689}