blob: f1ab0be32ce715ec12137da1ec561e4fbee4f373 [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;
20import android.os.Binder;
Narayan Kamatha0a28082017-07-31 15:58:59 +010021import android.os.Build;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -070022import android.os.RemoteException;
Narayan Kamatha0a28082017-07-31 15:58:59 +010023import android.system.ErrnoException;
24import android.system.OsConstants;
25import android.system.StructRlimit;
Andreas Gampe032a9292017-07-21 11:41:00 -070026import com.android.internal.os.ZygoteConnectionConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import com.android.server.am.ActivityManagerService;
28
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.BroadcastReceiver;
30import android.content.ContentResolver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
Steven Moreland6b47c542017-03-21 12:52:16 -070034import android.hidl.manager.V1_0.IServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.os.Debug;
36import android.os.Handler;
Jeff Brown6f357d32014-01-15 20:40:55 -080037import android.os.IPowerManager;
John Michelau11641522013-03-18 18:28:23 -050038import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.os.Process;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080040import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.os.SystemClock;
42import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.util.EventLog;
Dan Egnor9bdc94b2010-03-04 14:20:31 -080044import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080045import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046
Dan Egnor9bdc94b2010-03-04 14:20:31 -080047import java.io.File;
Colin Cross5df1d872012-11-29 11:42:11 -080048import java.io.FileWriter;
49import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import java.util.ArrayList;
Steven Moreland6b47c542017-03-21 12:52:16 -070051import java.util.Arrays;
Narayan Kamatha0a28082017-07-31 15:58:59 +010052import java.util.Collections;
Steven Moreland6b47c542017-03-21 12:52:16 -070053import java.util.HashSet;
54import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055
56/** This class calls its monitor every minute. Killing this process if they don't return **/
57public class Watchdog extends Thread {
58 static final String TAG = "Watchdog";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60 // Set this to true to use debug default values.
61 static final boolean DB = false;
62
Andreas Gampe032a9292017-07-21 11:41:00 -070063 // Note 1: Do not lower this value below thirty seconds without tightening the invoke-with
64 // timeout in com.android.internal.os.ZygoteConnection, or wrapped applications
65 // can trigger the watchdog.
66 // Note 2: The debug value is already below the wait time in ZygoteConnection. Wrapped
67 // applications may not work with a debug build. CTS will fail.
Christopher Tatee6f81cf2013-10-23 17:28:27 -070068 static final long DEFAULT_TIMEOUT = DB ? 10*1000 : 60*1000;
69 static final long CHECK_INTERVAL = DEFAULT_TIMEOUT / 2;
70
71 // These are temporally ordered: larger values as lateness increases
72 static final int COMPLETED = 0;
73 static final int WAITING = 1;
74 static final int WAITED_HALF = 2;
75 static final int OVERDUE = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076
Igor Murashkin44d04aa2013-10-23 10:56:02 -070077 // Which native processes to dump into dropbox's stack traces
78 public static final String[] NATIVE_STACKS_OF_INTEREST = new String[] {
Andy Hung3a64ecb2016-03-09 13:55:58 -080079 "/system/bin/audioserver",
Andy Hung689574a2016-04-13 19:27:43 -070080 "/system/bin/cameraserver",
81 "/system/bin/drmserver",
82 "/system/bin/mediadrmserver",
Dianne Hackbornf72467a2012-06-08 17:23:59 -070083 "/system/bin/mediaserver",
84 "/system/bin/sdcard",
Eric Laurent05d4e352016-03-14 18:49:08 -070085 "/system/bin/surfaceflinger",
Andy Hung689574a2016-04-13 19:27:43 -070086 "media.extractor", // system/bin/mediaextractor
Andy Hungb1c4c932018-01-04 12:05:43 -080087 "media.metrics", // system/bin/mediametrics
Chong Zhange55e6e02017-06-02 10:52:04 -070088 "media.codec", // vendor/bin/hw/android.hardware.media.omx@1.0-service
Andreas Gampecf9e79b2016-05-11 18:41:25 -070089 "com.android.bluetooth", // Bluetooth service
Rafal Slawike35d8f82018-10-01 11:39:58 +010090 "/system/bin/statsd", // Stats daemon
Dianne Hackbornf72467a2012-06-08 17:23:59 -070091 };
92
Steven Moreland6b47c542017-03-21 12:52:16 -070093 public static final List<String> HAL_INTERFACES_OF_INTEREST = Arrays.asList(
94 "android.hardware.audio@2.0::IDevicesFactory",
Mikhail Naganov09f0c5a2018-04-30 15:58:31 -070095 "android.hardware.audio@4.0::IDevicesFactory",
Steven Moreland6b47c542017-03-21 12:52:16 -070096 "android.hardware.bluetooth@1.0::IBluetoothHci",
97 "android.hardware.camera.provider@2.4::ICameraProvider",
Chia-I Wu74debcd2017-04-21 11:14:22 -070098 "android.hardware.graphics.composer@2.1::IComposer",
Yifan Honge8ea5222018-11-27 16:42:13 -080099 "android.hardware.health@2.0::IHealth",
Peng Xu102122fb2017-07-11 21:12:11 -0700100 "android.hardware.media.omx@1.0::IOmx",
Pawin Vongmasaf22f5f72018-04-18 07:01:47 -0700101 "android.hardware.media.omx@1.0::IOmxStore",
Peng Xu102122fb2017-07-11 21:12:11 -0700102 "android.hardware.sensors@1.0::ISensors",
103 "android.hardware.vr@1.0::IVr"
Steven Moreland6b47c542017-03-21 12:52:16 -0700104 );
105
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 static Watchdog sWatchdog;
107
108 /* This handler will be used to post message back onto the main thread */
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700109 final ArrayList<HandlerChecker> mHandlerCheckers = new ArrayList<>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700110 final HandlerChecker mMonitorChecker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 ContentResolver mResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 ActivityManagerService mActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 int mPhonePid;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700115 IActivityController mController;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700116 boolean mAllowRestart = true;
Narayan Kamatha0a28082017-07-31 15:58:59 +0100117 final OpenFdMonitor mOpenFdMonitor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 /**
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700120 * Used for checking status of handle threads and scheduling monitor callbacks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700122 public final class HandlerChecker implements Runnable {
123 private final Handler mHandler;
124 private final String mName;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700125 private final long mWaitMax;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700126 private final ArrayList<Monitor> mMonitors = new ArrayList<Monitor>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700127 private boolean mCompleted;
128 private Monitor mCurrentMonitor;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700129 private long mStartTime;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700130
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700131 HandlerChecker(Handler handler, String name, long waitMaxMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700132 mHandler = handler;
133 mName = name;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700134 mWaitMax = waitMaxMillis;
135 mCompleted = true;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700136 }
137
138 public void addMonitor(Monitor monitor) {
139 mMonitors.add(monitor);
140 }
141
142 public void scheduleCheckLocked() {
Jeff Brown6c7b41a2015-02-26 14:43:53 -0800143 if (mMonitors.size() == 0 && mHandler.getLooper().getQueue().isPolling()) {
144 // If the target looper has recently been polling, then
Dianne Hackbornefa92b22013-05-03 14:11:43 -0700145 // there is no reason to enqueue our checker on it since that
146 // is as good as it not being deadlocked. This avoid having
147 // to do a context switch to check the thread. Note that we
148 // only do this if mCheckReboot is false and we have no
149 // monitors, since those would need to be executed at this point.
150 mCompleted = true;
151 return;
152 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700153
154 if (!mCompleted) {
155 // we already have a check in flight, so no need
156 return;
157 }
158
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700159 mCompleted = false;
160 mCurrentMonitor = null;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700161 mStartTime = SystemClock.uptimeMillis();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700162 mHandler.postAtFrontOfQueue(this);
163 }
164
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700165 public boolean isOverdueLocked() {
166 return (!mCompleted) && (SystemClock.uptimeMillis() > mStartTime + mWaitMax);
167 }
168
169 public int getCompletionStateLocked() {
170 if (mCompleted) {
171 return COMPLETED;
172 } else {
173 long latency = SystemClock.uptimeMillis() - mStartTime;
174 if (latency < mWaitMax/2) {
175 return WAITING;
176 } else if (latency < mWaitMax) {
177 return WAITED_HALF;
178 }
179 }
180 return OVERDUE;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700181 }
182
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700183 public Thread getThread() {
184 return mHandler.getLooper().getThread();
185 }
186
187 public String getName() {
188 return mName;
189 }
190
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700191 public String describeBlockedStateLocked() {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700192 if (mCurrentMonitor == null) {
193 return "Blocked in handler on " + mName + " (" + getThread().getName() + ")";
194 } else {
195 return "Blocked in monitor " + mCurrentMonitor.getClass().getName()
196 + " on " + mName + " (" + getThread().getName() + ")";
197 }
John Michelau11641522013-03-18 18:28:23 -0500198 }
199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200 @Override
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700201 public void run() {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700202 final int size = mMonitors.size();
203 for (int i = 0 ; i < size ; i++) {
204 synchronized (Watchdog.this) {
205 mCurrentMonitor = mMonitors.get(i);
206 }
207 mCurrentMonitor.monitor();
208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700210 synchronized (Watchdog.this) {
211 mCompleted = true;
212 mCurrentMonitor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213 }
214 }
215 }
216
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 final class RebootRequestReceiver extends BroadcastReceiver {
218 @Override
219 public void onReceive(Context c, Intent intent) {
Dianne Hackbornf6438b12013-05-09 18:53:48 -0700220 if (intent.getIntExtra("nowait", 0) != 0) {
221 rebootSystem("Received ACTION_REBOOT broadcast");
222 return;
223 }
224 Slog.w(TAG, "Unsupported ACTION_REBOOT broadcast: " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800225 }
226 }
227
Wale Ogunwale517daec2015-04-15 10:27:24 -0700228 /** Monitor for checking the availability of binder threads. The monitor will block until
229 * there is a binder thread available to process in coming IPCs to make sure other processes
230 * can still communicate with the service.
231 */
232 private static final class BinderThreadMonitor implements Watchdog.Monitor {
233 @Override
234 public void monitor() {
235 Binder.blockUntilThreadAvailable();
236 }
237 }
238
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239 public interface Monitor {
240 void monitor();
241 }
242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 public static Watchdog getInstance() {
244 if (sWatchdog == null) {
245 sWatchdog = new Watchdog();
246 }
247
248 return sWatchdog;
249 }
250
251 private Watchdog() {
252 super("watchdog");
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700253 // Initialize handler checkers for each common thread we want to check. Note
254 // that we are not currently checking the background thread, since it can
255 // potentially hold longer running operations with no guarantees about the timeliness
256 // of operations there.
257
258 // The shared foreground thread is the main checker. It is where we
259 // will also dispatch monitor checks and do other work.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700260 mMonitorChecker = new HandlerChecker(FgThread.getHandler(),
261 "foreground thread", DEFAULT_TIMEOUT);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700262 mHandlerCheckers.add(mMonitorChecker);
263 // Add checker for main thread. We only do a quick check since there
264 // can be UI running on the thread.
265 mHandlerCheckers.add(new HandlerChecker(new Handler(Looper.getMainLooper()),
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700266 "main thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700267 // Add checker for shared UI thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700268 mHandlerCheckers.add(new HandlerChecker(UiThread.getHandler(),
269 "ui thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700270 // And also check IO thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700271 mHandlerCheckers.add(new HandlerChecker(IoThread.getHandler(),
272 "i/o thread", DEFAULT_TIMEOUT));
Jeff Brown4ccb8232014-01-16 22:16:42 -0800273 // And the display thread.
274 mHandlerCheckers.add(new HandlerChecker(DisplayThread.getHandler(),
275 "display thread", DEFAULT_TIMEOUT));
Wale Ogunwale517daec2015-04-15 10:27:24 -0700276
277 // Initialize monitor for Binder threads.
278 addMonitor(new BinderThreadMonitor());
Andreas Gampe032a9292017-07-21 11:41:00 -0700279
Narayan Kamatha0a28082017-07-31 15:58:59 +0100280 mOpenFdMonitor = OpenFdMonitor.create();
281
Andreas Gampe032a9292017-07-21 11:41:00 -0700282 // See the notes on DEFAULT_TIMEOUT.
283 assert DB ||
284 DEFAULT_TIMEOUT > ZygoteConnectionConstants.WRAPPED_PID_TIMEOUT_MILLIS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800285 }
286
Adam Lesinski182f73f2013-12-05 16:48:06 -0800287 public void init(Context context, ActivityManagerService activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800288 mResolver = context.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 mActivity = activity;
290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800291 context.registerReceiver(new RebootRequestReceiver(),
292 new IntentFilter(Intent.ACTION_REBOOT),
293 android.Manifest.permission.REBOOT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800294 }
295
Christopher Tatec27181c2010-06-30 14:41:09 -0700296 public void processStarted(String name, int pid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800297 synchronized (this) {
298 if ("com.android.phone".equals(name)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800299 mPhonePid = pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800300 }
301 }
302 }
303
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700304 public void setActivityController(IActivityController controller) {
305 synchronized (this) {
306 mController = controller;
307 }
308 }
309
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700310 public void setAllowRestart(boolean allowRestart) {
311 synchronized (this) {
312 mAllowRestart = allowRestart;
313 }
314 }
315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800316 public void addMonitor(Monitor monitor) {
317 synchronized (this) {
318 if (isAlive()) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700319 throw new RuntimeException("Monitors can't be added once the Watchdog is running");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 }
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700321 mMonitorChecker.addMonitor(monitor);
322 }
323 }
324
Jeff Brown6f357d32014-01-15 20:40:55 -0800325 public void addThread(Handler thread) {
326 addThread(thread, DEFAULT_TIMEOUT);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700327 }
328
Jeff Brown6f357d32014-01-15 20:40:55 -0800329 public void addThread(Handler thread, long timeoutMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700330 synchronized (this) {
331 if (isAlive()) {
332 throw new RuntimeException("Threads can't be added once the Watchdog is running");
333 }
Jeff Brown6f357d32014-01-15 20:40:55 -0800334 final String name = thread.getLooper().getThread().getName();
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700335 mHandlerCheckers.add(new HandlerChecker(thread, name, timeoutMillis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800336 }
337 }
338
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800339 /**
340 * Perform a full reboot of the system.
341 */
342 void rebootSystem(String reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800343 Slog.i(TAG, "Rebooting system because: " + reason);
Jeff Brown6f357d32014-01-15 20:40:55 -0800344 IPowerManager pms = (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE);
345 try {
346 pms.reboot(false, reason, false);
347 } catch (RemoteException ex) {
348 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800349 }
350
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700351 private int evaluateCheckerCompletionLocked() {
352 int state = COMPLETED;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700353 for (int i=0; i<mHandlerCheckers.size(); i++) {
354 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700355 state = Math.max(state, hc.getCompletionStateLocked());
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700356 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700357 return state;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700358 }
359
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700360 private ArrayList<HandlerChecker> getBlockedCheckersLocked() {
361 ArrayList<HandlerChecker> checkers = new ArrayList<HandlerChecker>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700362 for (int i=0; i<mHandlerCheckers.size(); i++) {
363 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700364 if (hc.isOverdueLocked()) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700365 checkers.add(hc);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700366 }
367 }
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700368 return checkers;
369 }
370
Narayan Kamatha0a28082017-07-31 15:58:59 +0100371 private String describeCheckersLocked(List<HandlerChecker> checkers) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700372 StringBuilder builder = new StringBuilder(128);
373 for (int i=0; i<checkers.size(); i++) {
374 if (builder.length() > 0) {
375 builder.append(", ");
376 }
377 builder.append(checkers.get(i).describeBlockedStateLocked());
378 }
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700379 return builder.toString();
380 }
381
Steven Moreland6b47c542017-03-21 12:52:16 -0700382 private ArrayList<Integer> getInterestingHalPids() {
383 try {
384 IServiceManager serviceManager = IServiceManager.getService();
385 ArrayList<IServiceManager.InstanceDebugInfo> dump =
386 serviceManager.debugDump();
387 HashSet<Integer> pids = new HashSet<>();
388 for (IServiceManager.InstanceDebugInfo info : dump) {
389 if (info.pid == IServiceManager.PidConstant.NO_PID) {
390 continue;
391 }
392
393 if (!HAL_INTERFACES_OF_INTEREST.contains(info.interfaceName)) {
394 continue;
395 }
396
397 pids.add(info.pid);
398 }
399 return new ArrayList<Integer>(pids);
400 } catch (RemoteException e) {
401 return new ArrayList<Integer>();
402 }
403 }
404
405 private ArrayList<Integer> getInterestingNativePids() {
406 ArrayList<Integer> pids = getInterestingHalPids();
407
408 int[] nativePids = Process.getPidsForCommands(NATIVE_STACKS_OF_INTEREST);
409 if (nativePids != null) {
410 pids.ensureCapacity(pids.size() + nativePids.length);
411 for (int i : nativePids) {
412 pids.add(i);
413 }
414 }
415
416 return pids;
417 }
418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800419 @Override
420 public void run() {
Christopher Tate6ee412d2010-05-28 12:01:56 -0700421 boolean waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422 while (true) {
Narayan Kamatha0a28082017-07-31 15:58:59 +0100423 final List<HandlerChecker> blockedCheckers;
Jeff Brown7dd2d192013-09-06 15:05:23 -0700424 final String subject;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700425 final boolean allowRestart;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700426 int debuggerWasConnected = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800427 synchronized (this) {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700428 long timeout = CHECK_INTERVAL;
429 // Make sure we (re)spin the checkers that have become idle within
430 // this wait-and-check interval
431 for (int i=0; i<mHandlerCheckers.size(); i++) {
432 HandlerChecker hc = mHandlerCheckers.get(i);
433 hc.scheduleCheckLocked();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800435
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700436 if (debuggerWasConnected > 0) {
437 debuggerWasConnected--;
438 }
439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800440 // NOTE: We use uptimeMillis() here because we do not want to increment the time we
441 // wait while asleep. If the device is asleep then the thing that we are waiting
Christopher Tate6ee412d2010-05-28 12:01:56 -0700442 // 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 -0800443 // positive on when to kill things.
444 long start = SystemClock.uptimeMillis();
Michael Wright8fa56f62013-04-01 16:36:05 -0700445 while (timeout > 0) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700446 if (Debug.isDebuggerConnected()) {
447 debuggerWasConnected = 2;
448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800449 try {
Michael Wright8fa56f62013-04-01 16:36:05 -0700450 wait(timeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 } catch (InterruptedException e) {
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800452 Log.wtf(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700454 if (Debug.isDebuggerConnected()) {
455 debuggerWasConnected = 2;
456 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700457 timeout = CHECK_INTERVAL - (SystemClock.uptimeMillis() - start);
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459
Narayan Kamatha0a28082017-07-31 15:58:59 +0100460 boolean fdLimitTriggered = false;
461 if (mOpenFdMonitor != null) {
462 fdLimitTriggered = mOpenFdMonitor.monitor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463 }
Michael Wright8fa56f62013-04-01 16:36:05 -0700464
Narayan Kamatha0a28082017-07-31 15:58:59 +0100465 if (!fdLimitTriggered) {
466 final int waitState = evaluateCheckerCompletionLocked();
467 if (waitState == COMPLETED) {
468 // The monitors have returned; reset
469 waitedHalf = false;
470 continue;
471 } else if (waitState == WAITING) {
472 // still waiting but within their configured intervals; back off and recheck
473 continue;
474 } else if (waitState == WAITED_HALF) {
475 if (!waitedHalf) {
476 // We've waited half the deadlock-detection interval. Pull a stack
477 // trace and wait another half.
478 ArrayList<Integer> pids = new ArrayList<Integer>();
479 pids.add(Process.myPid());
480 ActivityManagerService.dumpStackTraces(true, pids, null, null,
481 getInterestingNativePids());
482 waitedHalf = true;
483 }
484 continue;
485 }
486
487 // something is overdue!
488 blockedCheckers = getBlockedCheckersLocked();
489 subject = describeCheckersLocked(blockedCheckers);
490 } else {
491 blockedCheckers = Collections.emptyList();
492 subject = "Open FD high water mark reached";
493 }
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700494 allowRestart = mAllowRestart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800495 }
496
497 // If we got here, that means that the system is most likely hung.
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700498 // First collect stack traces from all threads of the system process.
499 // Then kill this process so that the system will restart.
Jeff Brown7dd2d192013-09-06 15:05:23 -0700500 EventLog.writeEvent(EventLogTags.WATCHDOG, subject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501
Steven Moreland6b47c542017-03-21 12:52:16 -0700502 ArrayList<Integer> pids = new ArrayList<>();
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800503 pids.add(Process.myPid());
Dan Egnor4bded072010-03-11 22:00:47 -0800504 if (mPhonePid > 0) pids.add(mPhonePid);
Christopher Tate6ee412d2010-05-28 12:01:56 -0700505 // Pass !waitedHalf so that just in case we somehow wind up here without having
506 // dumped the halfway stacks, we properly re-initialize the trace file.
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800507 final File stack = ActivityManagerService.dumpStackTraces(
Steven Moreland6b47c542017-03-21 12:52:16 -0700508 !waitedHalf, pids, null, null, getInterestingNativePids());
Dan Egnor4bded072010-03-11 22:00:47 -0800509
510 // Give some extra time to make sure the stack traces get written.
511 // The system's been hanging for a minute, another second or two won't hurt much.
512 SystemClock.sleep(2000);
513
Guang Zhu0620c452014-10-29 14:31:48 -0700514 // Trigger the kernel to dump all blocked threads, and backtraces on all CPUs to the kernel log
515 doSysRq('w');
516 doSysRq('l');
Colin Cross5df1d872012-11-29 11:42:11 -0800517
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800518 // Try to add the error to the dropbox, but assuming that the ActivityManager
519 // itself may be deadlocked. (which has happened, causing this statement to
520 // deadlock and the watchdog as a whole to be ineffective)
521 Thread dropboxThread = new Thread("watchdogWriteToDropbox") {
522 public void run() {
523 mActivity.addErrorToDropBox(
Jeff Sharkeya353d262011-10-28 11:12:06 -0700524 "watchdog", null, "system_server", null, null,
Jeff Brown7dd2d192013-09-06 15:05:23 -0700525 subject, null, stack, null);
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800526 }
527 };
528 dropboxThread.start();
529 try {
530 dropboxThread.join(2000); // wait up to 2 seconds for it to return.
531 } catch (InterruptedException ignored) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800532
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700533 IActivityController controller;
534 synchronized (this) {
535 controller = mController;
536 }
537 if (controller != null) {
538 Slog.i(TAG, "Reporting stuck state to activity controller");
539 try {
540 Binder.setDumpDisabled("Service dumps disabled due to hung system process.");
541 // 1 = keep waiting, -1 = kill system
Jeff Brown7dd2d192013-09-06 15:05:23 -0700542 int res = controller.systemNotResponding(subject);
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700543 if (res >= 0) {
544 Slog.i(TAG, "Activity controller requested to coninue to wait");
545 waitedHalf = false;
546 continue;
547 }
548 } catch (RemoteException e) {
549 }
550 }
551
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700552 // Only kill the process if the debugger is not attached.
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700553 if (Debug.isDebuggerConnected()) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700554 debuggerWasConnected = 2;
555 }
556 if (debuggerWasConnected >= 2) {
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700557 Slog.w(TAG, "Debugger connected: Watchdog is *not* killing the system process");
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700558 } else if (debuggerWasConnected > 0) {
559 Slog.w(TAG, "Debugger was connected: Watchdog is *not* killing the system process");
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700560 } else if (!allowRestart) {
561 Slog.w(TAG, "Restart not allowed: Watchdog is *not* killing the system process");
562 } else {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700563 Slog.w(TAG, "*** WATCHDOG KILLING SYSTEM PROCESS: " + subject);
Andreas Gampe544416e2018-01-26 11:39:46 -0800564 WatchdogDiagnostics.diagnoseCheckers(blockedCheckers);
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700565 Slog.w(TAG, "*** GOODBYE!");
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700566 Process.killProcess(Process.myPid());
567 System.exit(10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 }
Christopher Tate6ee412d2010-05-28 12:01:56 -0700569
570 waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800571 }
572 }
Christopher Tateecaa7b42010-06-04 14:55:02 -0700573
Guang Zhu0620c452014-10-29 14:31:48 -0700574 private void doSysRq(char c) {
575 try {
576 FileWriter sysrq_trigger = new FileWriter("/proc/sysrq-trigger");
577 sysrq_trigger.write(c);
578 sysrq_trigger.close();
579 } catch (IOException e) {
580 Slog.w(TAG, "Failed to write to /proc/sysrq-trigger", e);
581 }
582 }
583
Narayan Kamatha0a28082017-07-31 15:58:59 +0100584 public static final class OpenFdMonitor {
585 /**
586 * Number of FDs below the soft limit that we trigger a runtime restart at. This was
587 * chosen arbitrarily, but will need to be at least 6 in order to have a sufficient number
588 * of FDs in reserve to complete a dump.
589 */
590 private static final int FD_HIGH_WATER_MARK = 12;
591
592 private final File mDumpDir;
593 private final File mFdHighWaterMark;
594
595 public static OpenFdMonitor create() {
596 // Only run the FD monitor on debuggable builds (such as userdebug and eng builds).
597 if (!Build.IS_DEBUGGABLE) {
598 return null;
599 }
600
Narayan Kamatha0a28082017-07-31 15:58:59 +0100601 final StructRlimit rlimit;
602 try {
603 rlimit = android.system.Os.getrlimit(OsConstants.RLIMIT_NOFILE);
604 } catch (ErrnoException errno) {
605 Slog.w(TAG, "Error thrown from getrlimit(RLIMIT_NOFILE)", errno);
606 return null;
607 }
608
609 // The assumption we're making here is that FD numbers are allocated (more or less)
610 // sequentially, which is currently (and historically) true since open is currently
611 // specified to always return the lowest-numbered non-open file descriptor for the
612 // current process.
613 //
614 // We do this to avoid having to enumerate the contents of /proc/self/fd in order to
615 // count the number of descriptors open in the process.
616 final File fdThreshold = new File("/proc/self/fd/" + (rlimit.rlim_cur - FD_HIGH_WATER_MARK));
Elliott Hughes4e4caa72018-03-23 11:06:36 -0700617 return new OpenFdMonitor(new File("/data/anr"), fdThreshold);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100618 }
619
620 OpenFdMonitor(File dumpDir, File fdThreshold) {
621 mDumpDir = dumpDir;
622 mFdHighWaterMark = fdThreshold;
623 }
624
625 private void dumpOpenDescriptors() {
626 try {
627 File dumpFile = File.createTempFile("anr_fd_", "", mDumpDir);
628 java.lang.Process proc = new ProcessBuilder()
629 .command("/system/bin/lsof", "-p", String.valueOf(Process.myPid()))
630 .redirectErrorStream(true)
631 .redirectOutput(dumpFile)
632 .start();
633
634 int returnCode = proc.waitFor();
635 if (returnCode != 0) {
636 Slog.w(TAG, "Unable to dump open descriptors, lsof return code: "
637 + returnCode);
638 dumpFile.delete();
639 }
640 } catch (IOException | InterruptedException ex) {
641 Slog.w(TAG, "Unable to dump open descriptors: " + ex);
642 }
643 }
644
645 /**
646 * @return {@code true} if the high water mark was breached and a dump was written,
647 * {@code false} otherwise.
648 */
649 public boolean monitor() {
650 if (mFdHighWaterMark.exists()) {
651 dumpOpenDescriptors();
652 return true;
653 }
654
655 return false;
656 }
657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800658}