blob: e7a8221dc523899f81719aca310cbb84c3f7cdab [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;
Nandana Dutt6647ef52018-07-12 17:02:57 +010024import android.system.Os;
Narayan Kamatha0a28082017-07-31 15:58:59 +010025import android.system.OsConstants;
26import android.system.StructRlimit;
Andreas Gampe032a9292017-07-21 11:41:00 -070027import com.android.internal.os.ZygoteConnectionConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import com.android.server.am.ActivityManagerService;
29
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.BroadcastReceiver;
31import android.content.ContentResolver;
32import android.content.Context;
33import android.content.Intent;
34import android.content.IntentFilter;
Steven Moreland6b47c542017-03-21 12:52:16 -070035import android.hidl.manager.V1_0.IServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.os.Debug;
37import android.os.Handler;
Jeff Brown6f357d32014-01-15 20:40:55 -080038import android.os.IPowerManager;
John Michelau11641522013-03-18 18:28:23 -050039import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.os.Process;
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -080041import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.os.SystemClock;
43import android.os.SystemProperties;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.util.EventLog;
Dan Egnor9bdc94b2010-03-04 14:20:31 -080045import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080046import android.util.Slog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047
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
65 // Set this to true to use debug default values.
66 static final boolean DB = false;
67
Andreas Gampe032a9292017-07-21 11:41:00 -070068 // Note 1: Do not lower this value below thirty seconds without tightening the invoke-with
69 // timeout in com.android.internal.os.ZygoteConnection, or wrapped applications
70 // can trigger the watchdog.
71 // Note 2: The debug value is already below the wait time in ZygoteConnection. Wrapped
72 // applications may not work with a debug build. CTS will fail.
Christopher Tatee6f81cf2013-10-23 17:28:27 -070073 static final long DEFAULT_TIMEOUT = DB ? 10*1000 : 60*1000;
74 static final long CHECK_INTERVAL = DEFAULT_TIMEOUT / 2;
75
76 // These are temporally ordered: larger values as lateness increases
77 static final int COMPLETED = 0;
78 static final int WAITING = 1;
79 static final int WAITED_HALF = 2;
80 static final int OVERDUE = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081
Igor Murashkin44d04aa2013-10-23 10:56:02 -070082 // Which native processes to dump into dropbox's stack traces
83 public static final String[] NATIVE_STACKS_OF_INTEREST = new String[] {
Andy Hung3a64ecb2016-03-09 13:55:58 -080084 "/system/bin/audioserver",
Andy Hung689574a2016-04-13 19:27:43 -070085 "/system/bin/cameraserver",
86 "/system/bin/drmserver",
87 "/system/bin/mediadrmserver",
Dianne Hackbornf72467a2012-06-08 17:23:59 -070088 "/system/bin/mediaserver",
89 "/system/bin/sdcard",
Eric Laurent05d4e352016-03-14 18:49:08 -070090 "/system/bin/surfaceflinger",
Andy Hung689574a2016-04-13 19:27:43 -070091 "media.extractor", // system/bin/mediaextractor
Andy Hungb1c4c932018-01-04 12:05:43 -080092 "media.metrics", // system/bin/mediametrics
Chong Zhange55e6e02017-06-02 10:52:04 -070093 "media.codec", // vendor/bin/hw/android.hardware.media.omx@1.0-service
Andreas Gampecf9e79b2016-05-11 18:41:25 -070094 "com.android.bluetooth", // Bluetooth service
Andreas Gampee54440c2018-01-24 17:55:17 -080095 "statsd", // Stats daemon
Dianne Hackbornf72467a2012-06-08 17:23:59 -070096 };
97
Steven Moreland6b47c542017-03-21 12:52:16 -070098 public static final List<String> HAL_INTERFACES_OF_INTEREST = Arrays.asList(
99 "android.hardware.audio@2.0::IDevicesFactory",
Mikhail Naganov09f0c5a2018-04-30 15:58:31 -0700100 "android.hardware.audio@4.0::IDevicesFactory",
Steven Moreland6b47c542017-03-21 12:52:16 -0700101 "android.hardware.bluetooth@1.0::IBluetoothHci",
102 "android.hardware.camera.provider@2.4::ICameraProvider",
Chia-I Wu74debcd2017-04-21 11:14:22 -0700103 "android.hardware.graphics.composer@2.1::IComposer",
Peng Xu102122fb2017-07-11 21:12:11 -0700104 "android.hardware.media.omx@1.0::IOmx",
Pawin Vongmasaf22f5f72018-04-18 07:01:47 -0700105 "android.hardware.media.omx@1.0::IOmxStore",
Peng Xu102122fb2017-07-11 21:12:11 -0700106 "android.hardware.sensors@1.0::ISensors",
107 "android.hardware.vr@1.0::IVr"
Steven Moreland6b47c542017-03-21 12:52:16 -0700108 );
109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 static Watchdog sWatchdog;
111
112 /* This handler will be used to post message back onto the main thread */
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700113 final ArrayList<HandlerChecker> mHandlerCheckers = new ArrayList<>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700114 final HandlerChecker mMonitorChecker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115 ContentResolver mResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 ActivityManagerService mActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 int mPhonePid;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700119 IActivityController mController;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700120 boolean mAllowRestart = true;
Narayan Kamatha0a28082017-07-31 15:58:59 +0100121 final OpenFdMonitor mOpenFdMonitor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 /**
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700124 * Used for checking status of handle threads and scheduling monitor callbacks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700126 public final class HandlerChecker implements Runnable {
127 private final Handler mHandler;
128 private final String mName;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700129 private final long mWaitMax;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700130 private final ArrayList<Monitor> mMonitors = new ArrayList<Monitor>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700131 private boolean mCompleted;
132 private Monitor mCurrentMonitor;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700133 private long mStartTime;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700134
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700135 HandlerChecker(Handler handler, String name, long waitMaxMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700136 mHandler = handler;
137 mName = name;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700138 mWaitMax = waitMaxMillis;
139 mCompleted = true;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700140 }
141
142 public void addMonitor(Monitor monitor) {
143 mMonitors.add(monitor);
144 }
145
146 public void scheduleCheckLocked() {
Jeff Brown6c7b41a2015-02-26 14:43:53 -0800147 if (mMonitors.size() == 0 && mHandler.getLooper().getQueue().isPolling()) {
148 // If the target looper has recently been polling, then
Dianne Hackbornefa92b22013-05-03 14:11:43 -0700149 // there is no reason to enqueue our checker on it since that
150 // is as good as it not being deadlocked. This avoid having
151 // to do a context switch to check the thread. Note that we
152 // only do this if mCheckReboot is false and we have no
153 // monitors, since those would need to be executed at this point.
154 mCompleted = true;
155 return;
156 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700157
158 if (!mCompleted) {
159 // we already have a check in flight, so no need
160 return;
161 }
162
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700163 mCompleted = false;
164 mCurrentMonitor = null;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700165 mStartTime = SystemClock.uptimeMillis();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700166 mHandler.postAtFrontOfQueue(this);
167 }
168
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700169 public boolean isOverdueLocked() {
170 return (!mCompleted) && (SystemClock.uptimeMillis() > mStartTime + mWaitMax);
171 }
172
173 public int getCompletionStateLocked() {
174 if (mCompleted) {
175 return COMPLETED;
176 } else {
177 long latency = SystemClock.uptimeMillis() - mStartTime;
178 if (latency < mWaitMax/2) {
179 return WAITING;
180 } else if (latency < mWaitMax) {
181 return WAITED_HALF;
182 }
183 }
184 return OVERDUE;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700185 }
186
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700187 public Thread getThread() {
188 return mHandler.getLooper().getThread();
189 }
190
191 public String getName() {
192 return mName;
193 }
194
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700195 public String describeBlockedStateLocked() {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700196 if (mCurrentMonitor == null) {
197 return "Blocked in handler on " + mName + " (" + getThread().getName() + ")";
198 } else {
199 return "Blocked in monitor " + mCurrentMonitor.getClass().getName()
200 + " on " + mName + " (" + getThread().getName() + ")";
201 }
John Michelau11641522013-03-18 18:28:23 -0500202 }
203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204 @Override
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700205 public void run() {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700206 final int size = mMonitors.size();
207 for (int i = 0 ; i < size ; i++) {
208 synchronized (Watchdog.this) {
209 mCurrentMonitor = mMonitors.get(i);
210 }
211 mCurrentMonitor.monitor();
212 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700214 synchronized (Watchdog.this) {
215 mCompleted = true;
216 mCurrentMonitor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217 }
218 }
219 }
220
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 final class RebootRequestReceiver extends BroadcastReceiver {
222 @Override
223 public void onReceive(Context c, Intent intent) {
Dianne Hackbornf6438b12013-05-09 18:53:48 -0700224 if (intent.getIntExtra("nowait", 0) != 0) {
225 rebootSystem("Received ACTION_REBOOT broadcast");
226 return;
227 }
228 Slog.w(TAG, "Unsupported ACTION_REBOOT broadcast: " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 }
230 }
231
Wale Ogunwale517daec2015-04-15 10:27:24 -0700232 /** Monitor for checking the availability of binder threads. The monitor will block until
233 * there is a binder thread available to process in coming IPCs to make sure other processes
234 * can still communicate with the service.
235 */
236 private static final class BinderThreadMonitor implements Watchdog.Monitor {
237 @Override
238 public void monitor() {
239 Binder.blockUntilThreadAvailable();
240 }
241 }
242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800243 public interface Monitor {
244 void monitor();
245 }
246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247 public static Watchdog getInstance() {
248 if (sWatchdog == null) {
249 sWatchdog = new Watchdog();
250 }
251
252 return sWatchdog;
253 }
254
255 private Watchdog() {
256 super("watchdog");
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700257 // Initialize handler checkers for each common thread we want to check. Note
258 // that we are not currently checking the background thread, since it can
259 // potentially hold longer running operations with no guarantees about the timeliness
260 // of operations there.
261
262 // The shared foreground thread is the main checker. It is where we
263 // will also dispatch monitor checks and do other work.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700264 mMonitorChecker = new HandlerChecker(FgThread.getHandler(),
265 "foreground thread", DEFAULT_TIMEOUT);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700266 mHandlerCheckers.add(mMonitorChecker);
267 // Add checker for main thread. We only do a quick check since there
268 // can be UI running on the thread.
269 mHandlerCheckers.add(new HandlerChecker(new Handler(Looper.getMainLooper()),
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700270 "main thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700271 // Add checker for shared UI thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700272 mHandlerCheckers.add(new HandlerChecker(UiThread.getHandler(),
273 "ui thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700274 // And also check IO thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700275 mHandlerCheckers.add(new HandlerChecker(IoThread.getHandler(),
276 "i/o thread", DEFAULT_TIMEOUT));
Jeff Brown4ccb8232014-01-16 22:16:42 -0800277 // And the display thread.
278 mHandlerCheckers.add(new HandlerChecker(DisplayThread.getHandler(),
279 "display thread", DEFAULT_TIMEOUT));
Wale Ogunwale517daec2015-04-15 10:27:24 -0700280
281 // Initialize monitor for Binder threads.
282 addMonitor(new BinderThreadMonitor());
Andreas Gampe032a9292017-07-21 11:41:00 -0700283
Narayan Kamatha0a28082017-07-31 15:58:59 +0100284 mOpenFdMonitor = OpenFdMonitor.create();
285
Andreas Gampe032a9292017-07-21 11:41:00 -0700286 // See the notes on DEFAULT_TIMEOUT.
287 assert DB ||
288 DEFAULT_TIMEOUT > ZygoteConnectionConstants.WRAPPED_PID_TIMEOUT_MILLIS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800289 }
290
Adam Lesinski182f73f2013-12-05 16:48:06 -0800291 public void init(Context context, ActivityManagerService activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 mResolver = context.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800293 mActivity = activity;
294
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 context.registerReceiver(new RebootRequestReceiver(),
296 new IntentFilter(Intent.ACTION_REBOOT),
297 android.Manifest.permission.REBOOT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 }
299
Christopher Tatec27181c2010-06-30 14:41:09 -0700300 public void processStarted(String name, int pid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 synchronized (this) {
302 if ("com.android.phone".equals(name)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800303 mPhonePid = pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 }
305 }
306 }
307
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700308 public void setActivityController(IActivityController controller) {
309 synchronized (this) {
310 mController = controller;
311 }
312 }
313
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700314 public void setAllowRestart(boolean allowRestart) {
315 synchronized (this) {
316 mAllowRestart = allowRestart;
317 }
318 }
319
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800320 public void addMonitor(Monitor monitor) {
321 synchronized (this) {
322 if (isAlive()) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700323 throw new RuntimeException("Monitors can't be added once the Watchdog is running");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800324 }
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700325 mMonitorChecker.addMonitor(monitor);
326 }
327 }
328
Jeff Brown6f357d32014-01-15 20:40:55 -0800329 public void addThread(Handler thread) {
330 addThread(thread, DEFAULT_TIMEOUT);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700331 }
332
Jeff Brown6f357d32014-01-15 20:40:55 -0800333 public void addThread(Handler thread, long timeoutMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700334 synchronized (this) {
335 if (isAlive()) {
336 throw new RuntimeException("Threads can't be added once the Watchdog is running");
337 }
Jeff Brown6f357d32014-01-15 20:40:55 -0800338 final String name = thread.getLooper().getThread().getName();
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700339 mHandlerCheckers.add(new HandlerChecker(thread, name, timeoutMillis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800340 }
341 }
342
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 /**
344 * Perform a full reboot of the system.
345 */
346 void rebootSystem(String reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800347 Slog.i(TAG, "Rebooting system because: " + reason);
Jeff Brown6f357d32014-01-15 20:40:55 -0800348 IPowerManager pms = (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE);
349 try {
350 pms.reboot(false, reason, false);
351 } catch (RemoteException ex) {
352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800353 }
354
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700355 private int evaluateCheckerCompletionLocked() {
356 int state = COMPLETED;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700357 for (int i=0; i<mHandlerCheckers.size(); i++) {
358 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700359 state = Math.max(state, hc.getCompletionStateLocked());
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700360 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700361 return state;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700362 }
363
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700364 private ArrayList<HandlerChecker> getBlockedCheckersLocked() {
365 ArrayList<HandlerChecker> checkers = new ArrayList<HandlerChecker>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700366 for (int i=0; i<mHandlerCheckers.size(); i++) {
367 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700368 if (hc.isOverdueLocked()) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700369 checkers.add(hc);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700370 }
371 }
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700372 return checkers;
373 }
374
Narayan Kamatha0a28082017-07-31 15:58:59 +0100375 private String describeCheckersLocked(List<HandlerChecker> checkers) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700376 StringBuilder builder = new StringBuilder(128);
377 for (int i=0; i<checkers.size(); i++) {
378 if (builder.length() > 0) {
379 builder.append(", ");
380 }
381 builder.append(checkers.get(i).describeBlockedStateLocked());
382 }
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700383 return builder.toString();
384 }
385
Steven Moreland6b47c542017-03-21 12:52:16 -0700386 private ArrayList<Integer> getInterestingHalPids() {
387 try {
388 IServiceManager serviceManager = IServiceManager.getService();
389 ArrayList<IServiceManager.InstanceDebugInfo> dump =
390 serviceManager.debugDump();
391 HashSet<Integer> pids = new HashSet<>();
392 for (IServiceManager.InstanceDebugInfo info : dump) {
393 if (info.pid == IServiceManager.PidConstant.NO_PID) {
394 continue;
395 }
396
397 if (!HAL_INTERFACES_OF_INTEREST.contains(info.interfaceName)) {
398 continue;
399 }
400
401 pids.add(info.pid);
402 }
403 return new ArrayList<Integer>(pids);
404 } catch (RemoteException e) {
405 return new ArrayList<Integer>();
406 }
407 }
408
409 private ArrayList<Integer> getInterestingNativePids() {
410 ArrayList<Integer> pids = getInterestingHalPids();
411
412 int[] nativePids = Process.getPidsForCommands(NATIVE_STACKS_OF_INTEREST);
413 if (nativePids != null) {
414 pids.ensureCapacity(pids.size() + nativePids.length);
415 for (int i : nativePids) {
416 pids.add(i);
417 }
418 }
419
420 return pids;
421 }
422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800423 @Override
424 public void run() {
Christopher Tate6ee412d2010-05-28 12:01:56 -0700425 boolean waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 while (true) {
Narayan Kamatha0a28082017-07-31 15:58:59 +0100427 final List<HandlerChecker> blockedCheckers;
Jeff Brown7dd2d192013-09-06 15:05:23 -0700428 final String subject;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700429 final boolean allowRestart;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700430 int debuggerWasConnected = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800431 synchronized (this) {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700432 long timeout = CHECK_INTERVAL;
433 // Make sure we (re)spin the checkers that have become idle within
434 // this wait-and-check interval
435 for (int i=0; i<mHandlerCheckers.size(); i++) {
436 HandlerChecker hc = mHandlerCheckers.get(i);
437 hc.scheduleCheckLocked();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700438 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800439
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700440 if (debuggerWasConnected > 0) {
441 debuggerWasConnected--;
442 }
443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800444 // NOTE: We use uptimeMillis() here because we do not want to increment the time we
445 // wait while asleep. If the device is asleep then the thing that we are waiting
Christopher Tate6ee412d2010-05-28 12:01:56 -0700446 // 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 -0800447 // positive on when to kill things.
448 long start = SystemClock.uptimeMillis();
Michael Wright8fa56f62013-04-01 16:36:05 -0700449 while (timeout > 0) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700450 if (Debug.isDebuggerConnected()) {
451 debuggerWasConnected = 2;
452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800453 try {
Michael Wright8fa56f62013-04-01 16:36:05 -0700454 wait(timeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800455 } catch (InterruptedException e) {
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800456 Log.wtf(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700458 if (Debug.isDebuggerConnected()) {
459 debuggerWasConnected = 2;
460 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700461 timeout = CHECK_INTERVAL - (SystemClock.uptimeMillis() - start);
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800463
Narayan Kamatha0a28082017-07-31 15:58:59 +0100464 boolean fdLimitTriggered = false;
465 if (mOpenFdMonitor != null) {
466 fdLimitTriggered = mOpenFdMonitor.monitor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800467 }
Michael Wright8fa56f62013-04-01 16:36:05 -0700468
Narayan Kamatha0a28082017-07-31 15:58:59 +0100469 if (!fdLimitTriggered) {
470 final int waitState = evaluateCheckerCompletionLocked();
471 if (waitState == COMPLETED) {
472 // The monitors have returned; reset
473 waitedHalf = false;
474 continue;
475 } else if (waitState == WAITING) {
476 // still waiting but within their configured intervals; back off and recheck
477 continue;
478 } else if (waitState == WAITED_HALF) {
479 if (!waitedHalf) {
480 // We've waited half the deadlock-detection interval. Pull a stack
481 // trace and wait another half.
482 ArrayList<Integer> pids = new ArrayList<Integer>();
483 pids.add(Process.myPid());
484 ActivityManagerService.dumpStackTraces(true, pids, null, null,
485 getInterestingNativePids());
486 waitedHalf = true;
487 }
488 continue;
489 }
490
491 // something is overdue!
492 blockedCheckers = getBlockedCheckersLocked();
493 subject = describeCheckersLocked(blockedCheckers);
494 } else {
495 blockedCheckers = Collections.emptyList();
496 subject = "Open FD high water mark reached";
497 }
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700498 allowRestart = mAllowRestart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800499 }
500
501 // If we got here, that means that the system is most likely hung.
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700502 // First collect stack traces from all threads of the system process.
503 // Then kill this process so that the system will restart.
Jeff Brown7dd2d192013-09-06 15:05:23 -0700504 EventLog.writeEvent(EventLogTags.WATCHDOG, subject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505
Steven Moreland6b47c542017-03-21 12:52:16 -0700506 ArrayList<Integer> pids = new ArrayList<>();
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800507 pids.add(Process.myPid());
Dan Egnor4bded072010-03-11 22:00:47 -0800508 if (mPhonePid > 0) pids.add(mPhonePid);
Christopher Tate6ee412d2010-05-28 12:01:56 -0700509 // Pass !waitedHalf so that just in case we somehow wind up here without having
510 // dumped the halfway stacks, we properly re-initialize the trace file.
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800511 final File stack = ActivityManagerService.dumpStackTraces(
Steven Moreland6b47c542017-03-21 12:52:16 -0700512 !waitedHalf, pids, null, null, getInterestingNativePids());
Dan Egnor4bded072010-03-11 22:00:47 -0800513
514 // Give some extra time to make sure the stack traces get written.
515 // The system's been hanging for a minute, another second or two won't hurt much.
516 SystemClock.sleep(2000);
517
Guang Zhu0620c452014-10-29 14:31:48 -0700518 // Trigger the kernel to dump all blocked threads, and backtraces on all CPUs to the kernel log
519 doSysRq('w');
520 doSysRq('l');
Colin Cross5df1d872012-11-29 11:42:11 -0800521
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800522 // Try to add the error to the dropbox, but assuming that the ActivityManager
523 // itself may be deadlocked. (which has happened, causing this statement to
524 // deadlock and the watchdog as a whole to be ineffective)
525 Thread dropboxThread = new Thread("watchdogWriteToDropbox") {
526 public void run() {
527 mActivity.addErrorToDropBox(
Jeff Sharkeya353d262011-10-28 11:12:06 -0700528 "watchdog", null, "system_server", null, null,
Jeff Brown7dd2d192013-09-06 15:05:23 -0700529 subject, null, stack, null);
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800530 }
531 };
532 dropboxThread.start();
533 try {
534 dropboxThread.join(2000); // wait up to 2 seconds for it to return.
535 } catch (InterruptedException ignored) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800536
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700537 IActivityController controller;
538 synchronized (this) {
539 controller = mController;
540 }
541 if (controller != null) {
542 Slog.i(TAG, "Reporting stuck state to activity controller");
543 try {
544 Binder.setDumpDisabled("Service dumps disabled due to hung system process.");
545 // 1 = keep waiting, -1 = kill system
Jeff Brown7dd2d192013-09-06 15:05:23 -0700546 int res = controller.systemNotResponding(subject);
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700547 if (res >= 0) {
548 Slog.i(TAG, "Activity controller requested to coninue to wait");
549 waitedHalf = false;
550 continue;
551 }
552 } catch (RemoteException e) {
553 }
554 }
555
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700556 // Only kill the process if the debugger is not attached.
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700557 if (Debug.isDebuggerConnected()) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700558 debuggerWasConnected = 2;
559 }
560 if (debuggerWasConnected >= 2) {
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700561 Slog.w(TAG, "Debugger connected: Watchdog is *not* killing the system process");
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700562 } else if (debuggerWasConnected > 0) {
563 Slog.w(TAG, "Debugger was connected: Watchdog is *not* killing the system process");
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700564 } else if (!allowRestart) {
565 Slog.w(TAG, "Restart not allowed: Watchdog is *not* killing the system process");
566 } else {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700567 Slog.w(TAG, "*** WATCHDOG KILLING SYSTEM PROCESS: " + subject);
Andreas Gampe544416e2018-01-26 11:39:46 -0800568 WatchdogDiagnostics.diagnoseCheckers(blockedCheckers);
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700569 Slog.w(TAG, "*** GOODBYE!");
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700570 Process.killProcess(Process.myPid());
571 System.exit(10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572 }
Christopher Tate6ee412d2010-05-28 12:01:56 -0700573
574 waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
576 }
Christopher Tateecaa7b42010-06-04 14:55:02 -0700577
Guang Zhu0620c452014-10-29 14:31:48 -0700578 private void doSysRq(char c) {
579 try {
580 FileWriter sysrq_trigger = new FileWriter("/proc/sysrq-trigger");
581 sysrq_trigger.write(c);
582 sysrq_trigger.close();
583 } catch (IOException e) {
584 Slog.w(TAG, "Failed to write to /proc/sysrq-trigger", e);
585 }
586 }
587
Narayan Kamatha0a28082017-07-31 15:58:59 +0100588 public static final class OpenFdMonitor {
589 /**
590 * Number of FDs below the soft limit that we trigger a runtime restart at. This was
591 * chosen arbitrarily, but will need to be at least 6 in order to have a sufficient number
592 * of FDs in reserve to complete a dump.
593 */
594 private static final int FD_HIGH_WATER_MARK = 12;
595
596 private final File mDumpDir;
597 private final File mFdHighWaterMark;
598
599 public static OpenFdMonitor create() {
600 // Only run the FD monitor on debuggable builds (such as userdebug and eng builds).
601 if (!Build.IS_DEBUGGABLE) {
602 return null;
603 }
604
Narayan Kamatha0a28082017-07-31 15:58:59 +0100605 final StructRlimit rlimit;
606 try {
607 rlimit = android.system.Os.getrlimit(OsConstants.RLIMIT_NOFILE);
608 } catch (ErrnoException errno) {
609 Slog.w(TAG, "Error thrown from getrlimit(RLIMIT_NOFILE)", errno);
610 return null;
611 }
612
613 // The assumption we're making here is that FD numbers are allocated (more or less)
614 // sequentially, which is currently (and historically) true since open is currently
615 // specified to always return the lowest-numbered non-open file descriptor for the
616 // current process.
617 //
618 // We do this to avoid having to enumerate the contents of /proc/self/fd in order to
619 // count the number of descriptors open in the process.
620 final File fdThreshold = new File("/proc/self/fd/" + (rlimit.rlim_cur - FD_HIGH_WATER_MARK));
Elliott Hughes4e4caa72018-03-23 11:06:36 -0700621 return new OpenFdMonitor(new File("/data/anr"), fdThreshold);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100622 }
623
624 OpenFdMonitor(File dumpDir, File fdThreshold) {
625 mDumpDir = dumpDir;
626 mFdHighWaterMark = fdThreshold;
627 }
628
Nandana Dutt6647ef52018-07-12 17:02:57 +0100629 /**
630 * Dumps open file descriptors and their full paths to a temporary file in {@code mDumpDir}.
631 */
Narayan Kamatha0a28082017-07-31 15:58:59 +0100632 private void dumpOpenDescriptors() {
Nandana Dutt6647ef52018-07-12 17:02:57 +0100633 // We cannot exec lsof to get more info about open file descriptors because a newly
634 // forked process will not have the permissions to readlink. Instead list all open
635 // descriptors from /proc/pid/fd and resolve them.
636 List<String> dumpInfo = new ArrayList<>();
637 String fdDirPath = String.format("/proc/%d/fd/", Process.myPid());
638 File[] fds = new File(fdDirPath).listFiles();
639 if (fds == null) {
640 dumpInfo.add("Unable to list " + fdDirPath);
641 } else {
642 for (File f : fds) {
643 String fdSymLink = f.getAbsolutePath();
644 String resolvedPath = "";
645 try {
646 resolvedPath = Os.readlink(fdSymLink);
647 } catch (ErrnoException ex) {
648 resolvedPath = ex.getMessage();
649 }
650 dumpInfo.add(fdSymLink + "\t" + resolvedPath);
651 }
652 }
653
654 // Dump the fds & paths to a temp file.
Narayan Kamatha0a28082017-07-31 15:58:59 +0100655 try {
656 File dumpFile = File.createTempFile("anr_fd_", "", mDumpDir);
Nandana Dutt6647ef52018-07-12 17:02:57 +0100657 Path out = Paths.get(dumpFile.getAbsolutePath());
658 Files.write(out, dumpInfo, StandardCharsets.UTF_8);
659 } catch (IOException ex) {
660 Slog.w(TAG, "Unable to write open descriptors to file: " + ex);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100661 }
662 }
663
664 /**
665 * @return {@code true} if the high water mark was breached and a dump was written,
666 * {@code false} otherwise.
667 */
668 public boolean monitor() {
669 if (mFdHighWaterMark.exists()) {
670 dumpOpenDescriptors();
671 return true;
672 }
673
674 return false;
675 }
676 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800677}