blob: 9cc550daa5a714320926b529bf3c5a91031a3ba6 [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;
46
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;
Nandana Dutt6647ef52018-07-12 17:02:57 +010050import java.nio.charset.StandardCharsets;
51import java.nio.file.Files;
52import java.nio.file.Path;
53import java.nio.file.Paths;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import java.util.ArrayList;
Steven Moreland6b47c542017-03-21 12:52:16 -070055import java.util.Arrays;
Narayan Kamatha0a28082017-07-31 15:58:59 +010056import java.util.Collections;
Steven Moreland6b47c542017-03-21 12:52:16 -070057import java.util.HashSet;
58import java.util.List;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059
60/** This class calls its monitor every minute. Killing this process if they don't return **/
61public class Watchdog extends Thread {
62 static final String TAG = "Watchdog";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063
Makoto Onukie276b442018-08-30 09:38:44 -070064 /** Debug flag. */
65 public static final boolean DEBUG = true; // STOPSHIP disable it (b/113252928)
Makoto Onuki99029542018-08-27 17:23:09 -070066
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067 // Set this to true to use debug default values.
68 static final boolean DB = false;
69
Andreas Gampe032a9292017-07-21 11:41:00 -070070 // Note 1: Do not lower this value below thirty seconds without tightening the invoke-with
71 // timeout in com.android.internal.os.ZygoteConnection, or wrapped applications
72 // can trigger the watchdog.
73 // Note 2: The debug value is already below the wait time in ZygoteConnection. Wrapped
74 // applications may not work with a debug build. CTS will fail.
Christopher Tatee6f81cf2013-10-23 17:28:27 -070075 static final long DEFAULT_TIMEOUT = DB ? 10*1000 : 60*1000;
76 static final long CHECK_INTERVAL = DEFAULT_TIMEOUT / 2;
77
78 // These are temporally ordered: larger values as lateness increases
79 static final int COMPLETED = 0;
80 static final int WAITING = 1;
81 static final int WAITED_HALF = 2;
82 static final int OVERDUE = 3;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083
Igor Murashkin44d04aa2013-10-23 10:56:02 -070084 // Which native processes to dump into dropbox's stack traces
85 public static final String[] NATIVE_STACKS_OF_INTEREST = new String[] {
Andy Hung3a64ecb2016-03-09 13:55:58 -080086 "/system/bin/audioserver",
Andy Hung689574a2016-04-13 19:27:43 -070087 "/system/bin/cameraserver",
88 "/system/bin/drmserver",
89 "/system/bin/mediadrmserver",
Dianne Hackbornf72467a2012-06-08 17:23:59 -070090 "/system/bin/mediaserver",
91 "/system/bin/sdcard",
Eric Laurent05d4e352016-03-14 18:49:08 -070092 "/system/bin/surfaceflinger",
Andy Hung689574a2016-04-13 19:27:43 -070093 "media.extractor", // system/bin/mediaextractor
Andy Hungb1c4c932018-01-04 12:05:43 -080094 "media.metrics", // system/bin/mediametrics
Chong Zhange55e6e02017-06-02 10:52:04 -070095 "media.codec", // vendor/bin/hw/android.hardware.media.omx@1.0-service
Andreas Gampecf9e79b2016-05-11 18:41:25 -070096 "com.android.bluetooth", // Bluetooth service
Rafal Slawike35d8f82018-10-01 11:39:58 +010097 "/system/bin/statsd", // Stats daemon
Dianne Hackbornf72467a2012-06-08 17:23:59 -070098 };
99
Steven Moreland6b47c542017-03-21 12:52:16 -0700100 public static final List<String> HAL_INTERFACES_OF_INTEREST = Arrays.asList(
101 "android.hardware.audio@2.0::IDevicesFactory",
Mikhail Naganov09f0c5a2018-04-30 15:58:31 -0700102 "android.hardware.audio@4.0::IDevicesFactory",
Steven Moreland6b47c542017-03-21 12:52:16 -0700103 "android.hardware.bluetooth@1.0::IBluetoothHci",
104 "android.hardware.camera.provider@2.4::ICameraProvider",
Chia-I Wu49569e32018-08-01 09:59:02 -0700105 "android.hardware.graphics.allocator@2.0::IAllocator",
Chia-I Wu74debcd2017-04-21 11:14:22 -0700106 "android.hardware.graphics.composer@2.1::IComposer",
Peng Xu102122fb2017-07-11 21:12:11 -0700107 "android.hardware.media.omx@1.0::IOmx",
Pawin Vongmasaf22f5f72018-04-18 07:01:47 -0700108 "android.hardware.media.omx@1.0::IOmxStore",
Peng Xu102122fb2017-07-11 21:12:11 -0700109 "android.hardware.sensors@1.0::ISensors",
110 "android.hardware.vr@1.0::IVr"
Steven Moreland6b47c542017-03-21 12:52:16 -0700111 );
112
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113 static Watchdog sWatchdog;
114
115 /* This handler will be used to post message back onto the main thread */
Wale Ogunwaled7fdd022015-04-13 16:22:38 -0700116 final ArrayList<HandlerChecker> mHandlerCheckers = new ArrayList<>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700117 final HandlerChecker mMonitorChecker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 ContentResolver mResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 ActivityManagerService mActivity;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 int mPhonePid;
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700122 IActivityController mController;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700123 boolean mAllowRestart = true;
Narayan Kamatha0a28082017-07-31 15:58:59 +0100124 final OpenFdMonitor mOpenFdMonitor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 /**
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700127 * Used for checking status of handle threads and scheduling monitor callbacks.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 */
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700129 public final class HandlerChecker implements Runnable {
130 private final Handler mHandler;
131 private final String mName;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700132 private final long mWaitMax;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700133 private final ArrayList<Monitor> mMonitors = new ArrayList<Monitor>();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700134 private boolean mCompleted;
135 private Monitor mCurrentMonitor;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700136 private long mStartTime;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700137
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700138 HandlerChecker(Handler handler, String name, long waitMaxMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700139 mHandler = handler;
140 mName = name;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700141 mWaitMax = waitMaxMillis;
142 mCompleted = true;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700143 }
144
Makoto Onukie276b442018-08-30 09:38:44 -0700145 void addMonitorLocked(Monitor monitor) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700146 mMonitors.add(monitor);
147 }
148
149 public void scheduleCheckLocked() {
Jeff Brown6c7b41a2015-02-26 14:43:53 -0800150 if (mMonitors.size() == 0 && mHandler.getLooper().getQueue().isPolling()) {
151 // If the target looper has recently been polling, then
Dianne Hackbornefa92b22013-05-03 14:11:43 -0700152 // there is no reason to enqueue our checker on it since that
153 // is as good as it not being deadlocked. This avoid having
154 // to do a context switch to check the thread. Note that we
155 // only do this if mCheckReboot is false and we have no
156 // monitors, since those would need to be executed at this point.
157 mCompleted = true;
158 return;
159 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700160
161 if (!mCompleted) {
162 // we already have a check in flight, so no need
163 return;
164 }
165
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700166 mCompleted = false;
167 mCurrentMonitor = null;
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700168 mStartTime = SystemClock.uptimeMillis();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700169 mHandler.postAtFrontOfQueue(this);
170 }
171
Makoto Onukie276b442018-08-30 09:38:44 -0700172 boolean isOverdueLocked() {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700173 return (!mCompleted) && (SystemClock.uptimeMillis() > mStartTime + mWaitMax);
174 }
175
176 public int getCompletionStateLocked() {
177 if (mCompleted) {
178 return COMPLETED;
179 } else {
180 long latency = SystemClock.uptimeMillis() - mStartTime;
181 if (latency < mWaitMax/2) {
182 return WAITING;
183 } else if (latency < mWaitMax) {
184 return WAITED_HALF;
185 }
186 }
187 return OVERDUE;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700188 }
189
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700190 public Thread getThread() {
191 return mHandler.getLooper().getThread();
192 }
193
194 public String getName() {
195 return mName;
196 }
197
Makoto Onukie276b442018-08-30 09:38:44 -0700198 String describeBlockedStateLocked() {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700199 if (mCurrentMonitor == null) {
200 return "Blocked in handler on " + mName + " (" + getThread().getName() + ")";
201 } else {
202 return "Blocked in monitor " + mCurrentMonitor.getClass().getName()
203 + " on " + mName + " (" + getThread().getName() + ")";
204 }
John Michelau11641522013-03-18 18:28:23 -0500205 }
206
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207 @Override
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700208 public void run() {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700209 final int size = mMonitors.size();
210 for (int i = 0 ; i < size ; i++) {
211 synchronized (Watchdog.this) {
212 mCurrentMonitor = mMonitors.get(i);
213 }
214 mCurrentMonitor.monitor();
215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700217 synchronized (Watchdog.this) {
218 mCompleted = true;
219 mCurrentMonitor = null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220 }
221 }
222 }
223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 final class RebootRequestReceiver extends BroadcastReceiver {
225 @Override
226 public void onReceive(Context c, Intent intent) {
Dianne Hackbornf6438b12013-05-09 18:53:48 -0700227 if (intent.getIntExtra("nowait", 0) != 0) {
228 rebootSystem("Received ACTION_REBOOT broadcast");
229 return;
230 }
231 Slog.w(TAG, "Unsupported ACTION_REBOOT broadcast: " + intent);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232 }
233 }
234
Wale Ogunwale517daec2015-04-15 10:27:24 -0700235 /** Monitor for checking the availability of binder threads. The monitor will block until
236 * there is a binder thread available to process in coming IPCs to make sure other processes
237 * can still communicate with the service.
238 */
239 private static final class BinderThreadMonitor implements Watchdog.Monitor {
240 @Override
241 public void monitor() {
242 Binder.blockUntilThreadAvailable();
243 }
244 }
245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 public interface Monitor {
247 void monitor();
248 }
249
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250 public static Watchdog getInstance() {
251 if (sWatchdog == null) {
252 sWatchdog = new Watchdog();
253 }
254
255 return sWatchdog;
256 }
257
258 private Watchdog() {
259 super("watchdog");
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700260 // Initialize handler checkers for each common thread we want to check. Note
261 // that we are not currently checking the background thread, since it can
262 // potentially hold longer running operations with no guarantees about the timeliness
263 // of operations there.
264
265 // The shared foreground thread is the main checker. It is where we
266 // will also dispatch monitor checks and do other work.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700267 mMonitorChecker = new HandlerChecker(FgThread.getHandler(),
268 "foreground thread", DEFAULT_TIMEOUT);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700269 mHandlerCheckers.add(mMonitorChecker);
270 // Add checker for main thread. We only do a quick check since there
271 // can be UI running on the thread.
272 mHandlerCheckers.add(new HandlerChecker(new Handler(Looper.getMainLooper()),
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700273 "main thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700274 // Add checker for shared UI thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700275 mHandlerCheckers.add(new HandlerChecker(UiThread.getHandler(),
276 "ui thread", DEFAULT_TIMEOUT));
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700277 // And also check IO thread.
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700278 mHandlerCheckers.add(new HandlerChecker(IoThread.getHandler(),
279 "i/o thread", DEFAULT_TIMEOUT));
Jeff Brown4ccb8232014-01-16 22:16:42 -0800280 // And the display thread.
281 mHandlerCheckers.add(new HandlerChecker(DisplayThread.getHandler(),
282 "display thread", DEFAULT_TIMEOUT));
Wale Ogunwale517daec2015-04-15 10:27:24 -0700283
284 // Initialize monitor for Binder threads.
285 addMonitor(new BinderThreadMonitor());
Andreas Gampe032a9292017-07-21 11:41:00 -0700286
Narayan Kamatha0a28082017-07-31 15:58:59 +0100287 mOpenFdMonitor = OpenFdMonitor.create();
288
Andreas Gampe032a9292017-07-21 11:41:00 -0700289 // See the notes on DEFAULT_TIMEOUT.
290 assert DB ||
291 DEFAULT_TIMEOUT > ZygoteConnectionConstants.WRAPPED_PID_TIMEOUT_MILLIS;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800292 }
293
Adam Lesinski182f73f2013-12-05 16:48:06 -0800294 public void init(Context context, ActivityManagerService activity) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800295 mResolver = context.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800296 mActivity = activity;
297
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800298 context.registerReceiver(new RebootRequestReceiver(),
299 new IntentFilter(Intent.ACTION_REBOOT),
300 android.Manifest.permission.REBOOT, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800301 }
302
Christopher Tatec27181c2010-06-30 14:41:09 -0700303 public void processStarted(String name, int pid) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800304 synchronized (this) {
305 if ("com.android.phone".equals(name)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800306 mPhonePid = pid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800307 }
308 }
309 }
310
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700311 public void setActivityController(IActivityController controller) {
312 synchronized (this) {
313 mController = controller;
314 }
315 }
316
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700317 public void setAllowRestart(boolean allowRestart) {
318 synchronized (this) {
319 mAllowRestart = allowRestart;
320 }
321 }
322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800323 public void addMonitor(Monitor monitor) {
324 synchronized (this) {
325 if (isAlive()) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700326 throw new RuntimeException("Monitors can't be added once the Watchdog is running");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800327 }
Makoto Onukie276b442018-08-30 09:38:44 -0700328 mMonitorChecker.addMonitorLocked(monitor);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700329 }
330 }
331
Jeff Brown6f357d32014-01-15 20:40:55 -0800332 public void addThread(Handler thread) {
333 addThread(thread, DEFAULT_TIMEOUT);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700334 }
335
Jeff Brown6f357d32014-01-15 20:40:55 -0800336 public void addThread(Handler thread, long timeoutMillis) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700337 synchronized (this) {
338 if (isAlive()) {
339 throw new RuntimeException("Threads can't be added once the Watchdog is running");
340 }
Jeff Brown6f357d32014-01-15 20:40:55 -0800341 final String name = thread.getLooper().getThread().getName();
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700342 mHandlerCheckers.add(new HandlerChecker(thread, name, timeoutMillis));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800343 }
344 }
345
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800346 /**
347 * Perform a full reboot of the system.
348 */
349 void rebootSystem(String reason) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800350 Slog.i(TAG, "Rebooting system because: " + reason);
Jeff Brown6f357d32014-01-15 20:40:55 -0800351 IPowerManager pms = (IPowerManager)ServiceManager.getService(Context.POWER_SERVICE);
352 try {
353 pms.reboot(false, reason, false);
354 } catch (RemoteException ex) {
355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356 }
357
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700358 private int evaluateCheckerCompletionLocked() {
359 int state = COMPLETED;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700360 for (int i=0; i<mHandlerCheckers.size(); i++) {
361 HandlerChecker hc = mHandlerCheckers.get(i);
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700362 state = Math.max(state, hc.getCompletionStateLocked());
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700363 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700364 return state;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700365 }
366
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700367 private ArrayList<HandlerChecker> getBlockedCheckersLocked() {
368 ArrayList<HandlerChecker> checkers = new ArrayList<HandlerChecker>();
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 if (hc.isOverdueLocked()) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700372 checkers.add(hc);
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700373 }
374 }
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700375 return checkers;
376 }
377
Narayan Kamatha0a28082017-07-31 15:58:59 +0100378 private String describeCheckersLocked(List<HandlerChecker> checkers) {
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700379 StringBuilder builder = new StringBuilder(128);
380 for (int i=0; i<checkers.size(); i++) {
381 if (builder.length() > 0) {
382 builder.append(", ");
383 }
384 builder.append(checkers.get(i).describeBlockedStateLocked());
385 }
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700386 return builder.toString();
387 }
388
Steven Moreland6b47c542017-03-21 12:52:16 -0700389 private ArrayList<Integer> getInterestingHalPids() {
390 try {
391 IServiceManager serviceManager = IServiceManager.getService();
392 ArrayList<IServiceManager.InstanceDebugInfo> dump =
393 serviceManager.debugDump();
394 HashSet<Integer> pids = new HashSet<>();
395 for (IServiceManager.InstanceDebugInfo info : dump) {
396 if (info.pid == IServiceManager.PidConstant.NO_PID) {
397 continue;
398 }
399
400 if (!HAL_INTERFACES_OF_INTEREST.contains(info.interfaceName)) {
401 continue;
402 }
403
404 pids.add(info.pid);
405 }
406 return new ArrayList<Integer>(pids);
407 } catch (RemoteException e) {
408 return new ArrayList<Integer>();
409 }
410 }
411
412 private ArrayList<Integer> getInterestingNativePids() {
413 ArrayList<Integer> pids = getInterestingHalPids();
414
415 int[] nativePids = Process.getPidsForCommands(NATIVE_STACKS_OF_INTEREST);
416 if (nativePids != null) {
417 pids.ensureCapacity(pids.size() + nativePids.length);
418 for (int i : nativePids) {
419 pids.add(i);
420 }
421 }
422
423 return pids;
424 }
425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800426 @Override
427 public void run() {
Christopher Tate6ee412d2010-05-28 12:01:56 -0700428 boolean waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 while (true) {
Narayan Kamatha0a28082017-07-31 15:58:59 +0100430 final List<HandlerChecker> blockedCheckers;
Jeff Brown7dd2d192013-09-06 15:05:23 -0700431 final String subject;
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700432 final boolean allowRestart;
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700433 int debuggerWasConnected = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800434 synchronized (this) {
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700435 long timeout = CHECK_INTERVAL;
436 // Make sure we (re)spin the checkers that have become idle within
437 // this wait-and-check interval
438 for (int i=0; i<mHandlerCheckers.size(); i++) {
439 HandlerChecker hc = mHandlerCheckers.get(i);
440 hc.scheduleCheckLocked();
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800442
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700443 if (debuggerWasConnected > 0) {
444 debuggerWasConnected--;
445 }
446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800447 // NOTE: We use uptimeMillis() here because we do not want to increment the time we
448 // wait while asleep. If the device is asleep then the thing that we are waiting
Christopher Tate6ee412d2010-05-28 12:01:56 -0700449 // 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 -0800450 // positive on when to kill things.
451 long start = SystemClock.uptimeMillis();
Michael Wright8fa56f62013-04-01 16:36:05 -0700452 while (timeout > 0) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700453 if (Debug.isDebuggerConnected()) {
454 debuggerWasConnected = 2;
455 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800456 try {
Michael Wright8fa56f62013-04-01 16:36:05 -0700457 wait(timeout);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800458 } catch (InterruptedException e) {
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800459 Log.wtf(TAG, e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 }
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700461 if (Debug.isDebuggerConnected()) {
462 debuggerWasConnected = 2;
463 }
Christopher Tatee6f81cf2013-10-23 17:28:27 -0700464 timeout = CHECK_INTERVAL - (SystemClock.uptimeMillis() - start);
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800466
Narayan Kamatha0a28082017-07-31 15:58:59 +0100467 boolean fdLimitTriggered = false;
468 if (mOpenFdMonitor != null) {
469 fdLimitTriggered = mOpenFdMonitor.monitor();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800470 }
Michael Wright8fa56f62013-04-01 16:36:05 -0700471
Narayan Kamatha0a28082017-07-31 15:58:59 +0100472 if (!fdLimitTriggered) {
473 final int waitState = evaluateCheckerCompletionLocked();
474 if (waitState == COMPLETED) {
475 // The monitors have returned; reset
476 waitedHalf = false;
477 continue;
478 } else if (waitState == WAITING) {
479 // still waiting but within their configured intervals; back off and recheck
480 continue;
481 } else if (waitState == WAITED_HALF) {
482 if (!waitedHalf) {
Makoto Onuki99029542018-08-27 17:23:09 -0700483 if (DEBUG) Slog.d(TAG, "WAITED_HALF");
Narayan Kamatha0a28082017-07-31 15:58:59 +0100484 // We've waited half the deadlock-detection interval. Pull a stack
485 // trace and wait another half.
486 ArrayList<Integer> pids = new ArrayList<Integer>();
487 pids.add(Process.myPid());
Makoto Onukie276b442018-08-30 09:38:44 -0700488 ActivityManagerService.dumpStackTraces(pids, null, null,
Narayan Kamatha0a28082017-07-31 15:58:59 +0100489 getInterestingNativePids());
490 waitedHalf = true;
491 }
492 continue;
493 }
494
495 // something is overdue!
496 blockedCheckers = getBlockedCheckersLocked();
497 subject = describeCheckersLocked(blockedCheckers);
498 } else {
499 blockedCheckers = Collections.emptyList();
500 subject = "Open FD high water mark reached";
501 }
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700502 allowRestart = mAllowRestart;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 }
504
505 // If we got here, that means that the system is most likely hung.
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700506 // First collect stack traces from all threads of the system process.
507 // Then kill this process so that the system will restart.
Jeff Brown7dd2d192013-09-06 15:05:23 -0700508 EventLog.writeEvent(EventLogTags.WATCHDOG, subject);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800509
Steven Moreland6b47c542017-03-21 12:52:16 -0700510 ArrayList<Integer> pids = new ArrayList<>();
Dan Egnor9bdc94b2010-03-04 14:20:31 -0800511 pids.add(Process.myPid());
Dan Egnor4bded072010-03-11 22:00:47 -0800512 if (mPhonePid > 0) pids.add(mPhonePid);
Makoto Onukie276b442018-08-30 09:38:44 -0700513
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800514 final File stack = ActivityManagerService.dumpStackTraces(
Makoto Onukie276b442018-08-30 09:38:44 -0700515 pids, null, null, getInterestingNativePids());
Dan Egnor4bded072010-03-11 22:00:47 -0800516
517 // Give some extra time to make sure the stack traces get written.
518 // The system's been hanging for a minute, another second or two won't hurt much.
Makoto Onukie276b442018-08-30 09:38:44 -0700519 SystemClock.sleep(5000);
Dan Egnor4bded072010-03-11 22:00:47 -0800520
Guang Zhu0620c452014-10-29 14:31:48 -0700521 // Trigger the kernel to dump all blocked threads, and backtraces on all CPUs to the kernel log
522 doSysRq('w');
523 doSysRq('l');
Colin Cross5df1d872012-11-29 11:42:11 -0800524
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800525 // Try to add the error to the dropbox, but assuming that the ActivityManager
526 // itself may be deadlocked. (which has happened, causing this statement to
527 // deadlock and the watchdog as a whole to be ineffective)
528 Thread dropboxThread = new Thread("watchdogWriteToDropbox") {
529 public void run() {
530 mActivity.addErrorToDropBox(
Wale Ogunwale51cc98a2018-10-15 10:41:05 -0700531 "watchdog", null, "system_server", null, null, null,
Jeff Brown7dd2d192013-09-06 15:05:23 -0700532 subject, null, stack, null);
Brad Fitzpatrick9765c722011-01-14 11:28:22 -0800533 }
534 };
535 dropboxThread.start();
536 try {
537 dropboxThread.join(2000); // wait up to 2 seconds for it to return.
538 } catch (InterruptedException ignored) {}
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700540 IActivityController controller;
541 synchronized (this) {
542 controller = mController;
543 }
544 if (controller != null) {
545 Slog.i(TAG, "Reporting stuck state to activity controller");
546 try {
547 Binder.setDumpDisabled("Service dumps disabled due to hung system process.");
548 // 1 = keep waiting, -1 = kill system
Jeff Brown7dd2d192013-09-06 15:05:23 -0700549 int res = controller.systemNotResponding(subject);
Dianne Hackborn5b88a2f2013-05-03 16:25:11 -0700550 if (res >= 0) {
551 Slog.i(TAG, "Activity controller requested to coninue to wait");
552 waitedHalf = false;
553 continue;
554 }
555 } catch (RemoteException e) {
556 }
557 }
558
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700559 // Only kill the process if the debugger is not attached.
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700560 if (Debug.isDebuggerConnected()) {
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700561 debuggerWasConnected = 2;
562 }
563 if (debuggerWasConnected >= 2) {
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700564 Slog.w(TAG, "Debugger connected: Watchdog is *not* killing the system process");
Dianne Hackborn89ad4562014-08-24 16:45:38 -0700565 } else if (debuggerWasConnected > 0) {
566 Slog.w(TAG, "Debugger was connected: Watchdog is *not* killing the system process");
Dianne Hackborn8bd64df2013-05-06 16:07:26 -0700567 } else if (!allowRestart) {
568 Slog.w(TAG, "Restart not allowed: Watchdog is *not* killing the system process");
569 } else {
Jeff Brown7dd2d192013-09-06 15:05:23 -0700570 Slog.w(TAG, "*** WATCHDOG KILLING SYSTEM PROCESS: " + subject);
Andreas Gampe544416e2018-01-26 11:39:46 -0800571 WatchdogDiagnostics.diagnoseCheckers(blockedCheckers);
Dianne Hackbornfa012b32013-05-10 15:23:28 -0700572 Slog.w(TAG, "*** GOODBYE!");
Jean-Baptiste Queru784827b2012-09-04 13:35:12 -0700573 Process.killProcess(Process.myPid());
574 System.exit(10);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 }
Christopher Tate6ee412d2010-05-28 12:01:56 -0700576
577 waitedHalf = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800578 }
579 }
Christopher Tateecaa7b42010-06-04 14:55:02 -0700580
Guang Zhu0620c452014-10-29 14:31:48 -0700581 private void doSysRq(char c) {
582 try {
583 FileWriter sysrq_trigger = new FileWriter("/proc/sysrq-trigger");
584 sysrq_trigger.write(c);
585 sysrq_trigger.close();
586 } catch (IOException e) {
587 Slog.w(TAG, "Failed to write to /proc/sysrq-trigger", e);
588 }
589 }
590
Narayan Kamatha0a28082017-07-31 15:58:59 +0100591 public static final class OpenFdMonitor {
592 /**
593 * Number of FDs below the soft limit that we trigger a runtime restart at. This was
594 * chosen arbitrarily, but will need to be at least 6 in order to have a sufficient number
595 * of FDs in reserve to complete a dump.
596 */
597 private static final int FD_HIGH_WATER_MARK = 12;
598
599 private final File mDumpDir;
600 private final File mFdHighWaterMark;
601
602 public static OpenFdMonitor create() {
603 // Only run the FD monitor on debuggable builds (such as userdebug and eng builds).
604 if (!Build.IS_DEBUGGABLE) {
605 return null;
606 }
607
Narayan Kamatha0a28082017-07-31 15:58:59 +0100608 final StructRlimit rlimit;
609 try {
610 rlimit = android.system.Os.getrlimit(OsConstants.RLIMIT_NOFILE);
611 } catch (ErrnoException errno) {
612 Slog.w(TAG, "Error thrown from getrlimit(RLIMIT_NOFILE)", errno);
613 return null;
614 }
615
616 // The assumption we're making here is that FD numbers are allocated (more or less)
617 // sequentially, which is currently (and historically) true since open is currently
618 // specified to always return the lowest-numbered non-open file descriptor for the
619 // current process.
620 //
621 // We do this to avoid having to enumerate the contents of /proc/self/fd in order to
622 // count the number of descriptors open in the process.
623 final File fdThreshold = new File("/proc/self/fd/" + (rlimit.rlim_cur - FD_HIGH_WATER_MARK));
Elliott Hughes4e4caa72018-03-23 11:06:36 -0700624 return new OpenFdMonitor(new File("/data/anr"), fdThreshold);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100625 }
626
627 OpenFdMonitor(File dumpDir, File fdThreshold) {
628 mDumpDir = dumpDir;
629 mFdHighWaterMark = fdThreshold;
630 }
631
Nandana Dutt6647ef52018-07-12 17:02:57 +0100632 /**
633 * Dumps open file descriptors and their full paths to a temporary file in {@code mDumpDir}.
634 */
Narayan Kamatha0a28082017-07-31 15:58:59 +0100635 private void dumpOpenDescriptors() {
Nandana Dutt6647ef52018-07-12 17:02:57 +0100636 // We cannot exec lsof to get more info about open file descriptors because a newly
637 // forked process will not have the permissions to readlink. Instead list all open
638 // descriptors from /proc/pid/fd and resolve them.
639 List<String> dumpInfo = new ArrayList<>();
640 String fdDirPath = String.format("/proc/%d/fd/", Process.myPid());
641 File[] fds = new File(fdDirPath).listFiles();
642 if (fds == null) {
643 dumpInfo.add("Unable to list " + fdDirPath);
644 } else {
645 for (File f : fds) {
646 String fdSymLink = f.getAbsolutePath();
647 String resolvedPath = "";
648 try {
649 resolvedPath = Os.readlink(fdSymLink);
650 } catch (ErrnoException ex) {
651 resolvedPath = ex.getMessage();
652 }
653 dumpInfo.add(fdSymLink + "\t" + resolvedPath);
654 }
655 }
656
657 // Dump the fds & paths to a temp file.
Narayan Kamatha0a28082017-07-31 15:58:59 +0100658 try {
659 File dumpFile = File.createTempFile("anr_fd_", "", mDumpDir);
Nandana Dutt6647ef52018-07-12 17:02:57 +0100660 Path out = Paths.get(dumpFile.getAbsolutePath());
661 Files.write(out, dumpInfo, StandardCharsets.UTF_8);
662 } catch (IOException ex) {
663 Slog.w(TAG, "Unable to write open descriptors to file: " + ex);
Narayan Kamatha0a28082017-07-31 15:58:59 +0100664 }
665 }
666
667 /**
668 * @return {@code true} if the high water mark was breached and a dump was written,
669 * {@code false} otherwise.
670 */
671 public boolean monitor() {
672 if (mFdHighWaterMark.exists()) {
673 dumpOpenDescriptors();
674 return true;
675 }
676
677 return false;
678 }
679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800680}