blob: 36a913fb9c53d88ce74bb133d8fed00386274a55 [file] [log] [blame]
Adrian Roos20d7df32016-01-12 18:59:43 +01001/*
2 * Copyright (C) 2016 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.am;
18
19import com.android.internal.app.ProcessMap;
Adrian Roos90462222016-02-17 15:45:09 -080020import com.android.internal.logging.MetricsLogger;
Tamas Berghammer383db5eb2016-06-22 15:21:38 +010021import com.android.internal.logging.nano.MetricsProto;
Adrian Roos20d7df32016-01-12 18:59:43 +010022import com.android.internal.os.ProcessCpuTracker;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -070023import com.android.server.RescueParty;
Adrian Roos20d7df32016-01-12 18:59:43 +010024import com.android.server.Watchdog;
25
Adrian Roos20d7df32016-01-12 18:59:43 +010026import android.app.ActivityManager;
27import android.app.ActivityOptions;
28import android.app.ActivityThread;
29import android.app.AppOpsManager;
30import android.app.ApplicationErrorReport;
31import android.app.Dialog;
32import android.content.ActivityNotFoundException;
33import android.content.Context;
34import android.content.Intent;
35import android.content.pm.ApplicationInfo;
Adrian Roos20d7df32016-01-12 18:59:43 +010036import android.os.Binder;
Adrian Roos20d7df32016-01-12 18:59:43 +010037import android.os.Message;
38import android.os.Process;
39import android.os.RemoteException;
40import android.os.SystemClock;
41import android.os.SystemProperties;
42import android.os.UserHandle;
43import android.provider.Settings;
44import android.util.ArrayMap;
45import android.util.ArraySet;
46import android.util.EventLog;
47import android.util.Log;
48import android.util.Slog;
49import android.util.SparseArray;
50import android.util.TimeUtils;
51
52import java.io.File;
53import java.io.FileDescriptor;
54import java.io.PrintWriter;
55import java.util.ArrayList;
56import java.util.Collections;
57import java.util.HashMap;
Dianne Hackborn4d895942016-07-12 13:36:02 -070058import java.util.Set;
Adrian Roos20d7df32016-01-12 18:59:43 +010059
60import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST;
Dianne Hackborn9369efd2016-03-02 15:49:58 -080061import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
Adrian Roos20d7df32016-01-12 18:59:43 +010062import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
63import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
64import static com.android.server.am.ActivityManagerService.MY_PID;
65import static com.android.server.am.ActivityManagerService.SYSTEM_DEBUGGABLE;
66
67/**
68 * Controls error conditions in applications.
69 */
70class AppErrors {
71
72 private static final String TAG = TAG_WITH_CLASS_NAME ? "AppErrors" : TAG_AM;
73
74 private final ActivityManagerService mService;
75 private final Context mContext;
76
77 private ArraySet<String> mAppsNotReportingCrashes;
78
79 /**
80 * The last time that various processes have crashed since they were last explicitly started.
81 */
82 private final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<>();
83
84 /**
85 * The last time that various processes have crashed (not reset even when explicitly started).
86 */
87 private final ProcessMap<Long> mProcessCrashTimesPersistent = new ProcessMap<>();
88
89 /**
90 * Set of applications that we consider to be bad, and will reject
91 * incoming broadcasts from (which the user has no control over).
92 * Processes are added to this set when they have crashed twice within
93 * a minimum amount of time; they are removed from it when they are
94 * later restarted (hopefully due to some user action). The value is the
95 * time it was added to the list.
96 */
97 private final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<>();
98
99
100 AppErrors(Context context, ActivityManagerService service) {
101 mService = service;
102 mContext = context;
103 }
104
105 boolean dumpLocked(FileDescriptor fd, PrintWriter pw, boolean needSep,
106 String dumpPackage) {
107 if (!mProcessCrashTimes.getMap().isEmpty()) {
108 boolean printed = false;
109 final long now = SystemClock.uptimeMillis();
110 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
111 final int processCount = pmap.size();
112 for (int ip = 0; ip < processCount; ip++) {
113 final String pname = pmap.keyAt(ip);
114 final SparseArray<Long> uids = pmap.valueAt(ip);
115 final int uidCount = uids.size();
116 for (int i = 0; i < uidCount; i++) {
117 final int puid = uids.keyAt(i);
118 final ProcessRecord r = mService.mProcessNames.get(pname, puid);
119 if (dumpPackage != null && (r == null
120 || !r.pkgList.containsKey(dumpPackage))) {
121 continue;
122 }
123 if (!printed) {
124 if (needSep) pw.println();
125 needSep = true;
126 pw.println(" Time since processes crashed:");
127 printed = true;
128 }
129 pw.print(" Process "); pw.print(pname);
130 pw.print(" uid "); pw.print(puid);
131 pw.print(": last crashed ");
132 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
133 pw.println(" ago");
134 }
135 }
136 }
137
138 if (!mBadProcesses.getMap().isEmpty()) {
139 boolean printed = false;
140 final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap();
141 final int processCount = pmap.size();
142 for (int ip = 0; ip < processCount; ip++) {
143 final String pname = pmap.keyAt(ip);
144 final SparseArray<BadProcessInfo> uids = pmap.valueAt(ip);
145 final int uidCount = uids.size();
146 for (int i = 0; i < uidCount; i++) {
147 final int puid = uids.keyAt(i);
148 final ProcessRecord r = mService.mProcessNames.get(pname, puid);
149 if (dumpPackage != null && (r == null
150 || !r.pkgList.containsKey(dumpPackage))) {
151 continue;
152 }
153 if (!printed) {
154 if (needSep) pw.println();
155 needSep = true;
156 pw.println(" Bad processes:");
157 printed = true;
158 }
159 final BadProcessInfo info = uids.valueAt(i);
160 pw.print(" Bad process "); pw.print(pname);
161 pw.print(" uid "); pw.print(puid);
162 pw.print(": crashed at time "); pw.println(info.time);
163 if (info.shortMsg != null) {
164 pw.print(" Short msg: "); pw.println(info.shortMsg);
165 }
166 if (info.longMsg != null) {
167 pw.print(" Long msg: "); pw.println(info.longMsg);
168 }
169 if (info.stack != null) {
170 pw.println(" Stack:");
171 int lastPos = 0;
172 for (int pos = 0; pos < info.stack.length(); pos++) {
173 if (info.stack.charAt(pos) == '\n') {
174 pw.print(" ");
175 pw.write(info.stack, lastPos, pos-lastPos);
176 pw.println();
177 lastPos = pos+1;
178 }
179 }
180 if (lastPos < info.stack.length()) {
181 pw.print(" ");
182 pw.write(info.stack, lastPos, info.stack.length()-lastPos);
183 pw.println();
184 }
185 }
186 }
187 }
188 }
189 return needSep;
190 }
191
192 boolean isBadProcessLocked(ApplicationInfo info) {
193 return mBadProcesses.get(info.processName, info.uid) != null;
194 }
195
196 void clearBadProcessLocked(ApplicationInfo info) {
197 mBadProcesses.remove(info.processName, info.uid);
198 }
199
200 void resetProcessCrashTimeLocked(ApplicationInfo info) {
201 mProcessCrashTimes.remove(info.processName, info.uid);
202 }
203
204 void resetProcessCrashTimeLocked(boolean resetEntireUser, int appId, int userId) {
205 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
206 for (int ip = pmap.size() - 1; ip >= 0; ip--) {
207 SparseArray<Long> ba = pmap.valueAt(ip);
208 for (int i = ba.size() - 1; i >= 0; i--) {
209 boolean remove = false;
210 final int entUid = ba.keyAt(i);
211 if (!resetEntireUser) {
212 if (userId == UserHandle.USER_ALL) {
213 if (UserHandle.getAppId(entUid) == appId) {
214 remove = true;
215 }
216 } else {
217 if (entUid == UserHandle.getUid(userId, appId)) {
218 remove = true;
219 }
220 }
221 } else if (UserHandle.getUserId(entUid) == userId) {
222 remove = true;
223 }
224 if (remove) {
225 ba.removeAt(i);
226 }
227 }
228 if (ba.size() == 0) {
229 pmap.removeAt(ip);
230 }
231 }
232 }
233
234 void loadAppsNotReportingCrashesFromConfigLocked(String appsNotReportingCrashesConfig) {
235 if (appsNotReportingCrashesConfig != null) {
236 final String[] split = appsNotReportingCrashesConfig.split(",");
237 if (split.length > 0) {
238 mAppsNotReportingCrashes = new ArraySet<>();
239 Collections.addAll(mAppsNotReportingCrashes, split);
240 }
241 }
242 }
243
244 void killAppAtUserRequestLocked(ProcessRecord app, Dialog fromDialog) {
245 app.crashing = false;
246 app.crashingReport = null;
247 app.notResponding = false;
248 app.notRespondingReport = null;
249 if (app.anrDialog == fromDialog) {
250 app.anrDialog = null;
251 }
252 if (app.waitDialog == fromDialog) {
253 app.waitDialog = null;
254 }
255 if (app.pid > 0 && app.pid != MY_PID) {
256 handleAppCrashLocked(app, "user-terminated" /*reason*/,
257 null /*shortMsg*/, null /*longMsg*/, null /*stackTrace*/, null /*data*/);
258 app.kill("user request after error", true);
259 }
260 }
261
Christopher Tate8aa8fe12017-01-20 17:50:32 -0800262 /**
263 * Induce a crash in the given app.
264 *
265 * @param uid if nonnegative, the required matching uid of the target to crash
266 * @param initialPid fast-path match for the target to crash
267 * @param packageName fallback match if the stated pid is not found or doesn't match uid
268 * @param userId If nonnegative, required to identify a match by package name
269 * @param message
270 */
271 void scheduleAppCrashLocked(int uid, int initialPid, String packageName, int userId,
Adrian Roos20d7df32016-01-12 18:59:43 +0100272 String message) {
273 ProcessRecord proc = null;
274
275 // Figure out which process to kill. We don't trust that initialPid
276 // still has any relation to current pids, so must scan through the
277 // list.
278
279 synchronized (mService.mPidsSelfLocked) {
280 for (int i=0; i<mService.mPidsSelfLocked.size(); i++) {
281 ProcessRecord p = mService.mPidsSelfLocked.valueAt(i);
Christopher Tate8aa8fe12017-01-20 17:50:32 -0800282 if (uid >= 0 && p.uid != uid) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100283 continue;
284 }
285 if (p.pid == initialPid) {
286 proc = p;
287 break;
288 }
Christopher Tate8aa8fe12017-01-20 17:50:32 -0800289 if (p.pkgList.containsKey(packageName)
290 && (userId < 0 || p.userId == userId)) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100291 proc = p;
292 }
293 }
294 }
295
296 if (proc == null) {
297 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
298 + " initialPid=" + initialPid
Christopher Tate8aa8fe12017-01-20 17:50:32 -0800299 + " packageName=" + packageName
300 + " userId=" + userId);
Adrian Roos20d7df32016-01-12 18:59:43 +0100301 return;
302 }
303
Joe Onorato57190282016-04-20 15:37:49 -0700304 proc.scheduleCrash(message);
Adrian Roos20d7df32016-01-12 18:59:43 +0100305 }
306
307 /**
308 * Bring up the "unexpected error" dialog box for a crashing app.
309 * Deal with edge cases (intercepts from instrumented applications,
310 * ActivityController, error intent receivers, that sort of thing).
311 * @param r the application crashing
312 * @param crashInfo describing the failure
313 */
314 void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Mark Lub5e24992016-11-21 15:38:13 +0800315 final int callingPid = Binder.getCallingPid();
316 final int callingUid = Binder.getCallingUid();
317
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700318 final long origId = Binder.clearCallingIdentity();
319 try {
Mark Lub5e24992016-11-21 15:38:13 +0800320 crashApplicationInner(r, crashInfo, callingPid, callingUid);
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700321 } finally {
322 Binder.restoreCallingIdentity(origId);
323 }
324 }
325
Mark Lub5e24992016-11-21 15:38:13 +0800326 void crashApplicationInner(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo,
327 int callingPid, int callingUid) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100328 long timeMillis = System.currentTimeMillis();
329 String shortMsg = crashInfo.exceptionClassName;
330 String longMsg = crashInfo.exceptionMessage;
331 String stackTrace = crashInfo.stackTrace;
332 if (shortMsg != null && longMsg != null) {
333 longMsg = shortMsg + ": " + longMsg;
334 } else if (shortMsg != null) {
335 longMsg = shortMsg;
336 }
337
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -0700338 // If a persistent app is stuck in a crash loop, the device isn't very
339 // usable, so we want to consider sending out a rescue party.
340 if (r != null && r.persistent) {
341 RescueParty.notePersistentAppCrash(mContext, r.uid);
342 }
343
Adrian Roos20d7df32016-01-12 18:59:43 +0100344 AppErrorResult result = new AppErrorResult();
345 TaskRecord task;
346 synchronized (mService) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700347 /**
348 * If crash is handled by instance of {@link android.app.IActivityController},
349 * finish now and don't show the app error dialog.
350 */
351 if (handleAppCrashInActivityController(r, crashInfo, shortMsg, longMsg, stackTrace,
Mark Lub5e24992016-11-21 15:38:13 +0800352 timeMillis, callingPid, callingUid)) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700353 return;
Adrian Roos20d7df32016-01-12 18:59:43 +0100354 }
355
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700356 /**
357 * If this process was running instrumentation, finish now - it will be handled in
358 * {@link ActivityManagerService#handleAppDiedLocked}.
359 */
Dianne Hackborn34041732017-01-31 15:27:13 -0800360 if (r != null && r.instr != null) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100361 return;
362 }
363
364 // Log crash in battery stats.
365 if (r != null) {
366 mService.mBatteryStatsService.noteProcessCrash(r.processName, r.uid);
367 }
368
369 AppErrorDialog.Data data = new AppErrorDialog.Data();
370 data.result = result;
371 data.proc = r;
372
373 // If we can't identify the process or it's already exceeded its crash quota,
374 // quit right away without showing a crash dialog.
375 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, data)) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100376 return;
377 }
378
Wale Ogunwale9645b0f2016-09-12 10:49:35 -0700379 final Message msg = Message.obtain();
Adrian Roos20d7df32016-01-12 18:59:43 +0100380 msg.what = ActivityManagerService.SHOW_ERROR_UI_MSG;
381
382 task = data.task;
383 msg.obj = data;
384 mService.mUiHandler.sendMessage(msg);
Adrian Roos20d7df32016-01-12 18:59:43 +0100385 }
386
387 int res = result.get();
388
389 Intent appErrorIntent = null;
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700390 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_CRASH, res);
Adrian Roosad028c12016-05-17 14:30:42 -0700391 if (res == AppErrorDialog.TIMEOUT || res == AppErrorDialog.CANCEL) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700392 res = AppErrorDialog.FORCE_QUIT;
393 }
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700394 synchronized (mService) {
395 if (res == AppErrorDialog.MUTE) {
396 stopReportingCrashesLocked(r);
397 }
398 if (res == AppErrorDialog.RESTART) {
399 mService.removeProcessLocked(r, false, true, "crash");
400 if (task != null) {
401 try {
402 mService.startActivityFromRecents(task.taskId,
403 ActivityOptions.makeBasic().toBundle());
404 } catch (IllegalArgumentException e) {
405 // Hmm, that didn't work, app might have crashed before creating a
406 // recents entry. Let's see if we have a safe-to-restart intent.
Dianne Hackborn4d895942016-07-12 13:36:02 -0700407 final Set<String> cats = task.intent.getCategories();
408 if (cats != null && cats.contains(Intent.CATEGORY_LAUNCHER)) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700409 mService.startActivityInPackage(task.mCallingUid,
410 task.mCallingPackage, task.intent,
411 null, null, null, 0, 0,
412 ActivityOptions.makeBasic().toBundle(),
413 task.userId, null, null);
414 }
415 }
416 }
417 }
418 if (res == AppErrorDialog.FORCE_QUIT) {
419 long orig = Binder.clearCallingIdentity();
420 try {
421 // Kill it with fire!
422 mService.mStackSupervisor.handleAppCrashLocked(r);
423 if (!r.persistent) {
424 mService.removeProcessLocked(r, false, false, "crash");
425 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
426 }
427 } finally {
428 Binder.restoreCallingIdentity(orig);
429 }
430 }
431 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
432 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
433 }
434 if (r != null && !r.isolated && res != AppErrorDialog.RESTART) {
435 // XXX Can't keep track of crash time for isolated processes,
436 // since they don't have a persistent identity.
437 mProcessCrashTimes.put(r.info.processName, r.uid,
438 SystemClock.uptimeMillis());
439 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100440 }
441
442 if (appErrorIntent != null) {
443 try {
444 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
445 } catch (ActivityNotFoundException e) {
446 Slog.w(TAG, "bug report receiver dissappeared", e);
447 }
448 }
449 }
450
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700451 private boolean handleAppCrashInActivityController(ProcessRecord r,
452 ApplicationErrorReport.CrashInfo crashInfo,
453 String shortMsg, String longMsg,
Mark Lub5e24992016-11-21 15:38:13 +0800454 String stackTrace, long timeMillis,
455 int callingPid, int callingUid) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700456 if (mService.mController == null) {
457 return false;
458 }
459
460 try {
461 String name = r != null ? r.processName : null;
Mark Lub5e24992016-11-21 15:38:13 +0800462 int pid = r != null ? r.pid : callingPid;
463 int uid = r != null ? r.info.uid : callingUid;
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700464 if (!mService.mController.appCrashed(name, pid,
465 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
466 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"))
467 && "Native crash".equals(crashInfo.exceptionClassName)) {
468 Slog.w(TAG, "Skip killing native crashed app " + name
469 + "(" + pid + ") during testing");
470 } else {
471 Slog.w(TAG, "Force-killing crashed app " + name
472 + " at watcher's request");
473 if (r != null) {
474 if (!makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, null))
475 {
476 r.kill("crash", true);
477 }
478 } else {
479 // Huh.
480 Process.killProcess(pid);
481 ActivityManagerService.killProcessGroup(uid, pid);
482 }
483 }
484 return true;
485 }
486 } catch (RemoteException e) {
487 mService.mController = null;
488 Watchdog.getInstance().setActivityController(null);
489 }
490 return false;
491 }
492
Adrian Roos20d7df32016-01-12 18:59:43 +0100493 private boolean makeAppCrashingLocked(ProcessRecord app,
494 String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
495 app.crashing = true;
496 app.crashingReport = generateProcessError(app,
497 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
498 startAppProblemLocked(app);
499 app.stopFreezingAllLocked();
500 return handleAppCrashLocked(app, "force-crash" /*reason*/, shortMsg, longMsg, stackTrace,
501 data);
502 }
503
504 void startAppProblemLocked(ProcessRecord app) {
505 // If this app is not running under the current user, then we
506 // can't give it a report button because that would require
507 // launching the report UI under a different user.
508 app.errorReportReceiver = null;
509
510 for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) {
511 if (app.userId == userId) {
512 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
513 mContext, app.info.packageName, app.info.flags);
514 }
515 }
516 mService.skipCurrentReceiverLocked(app);
517 }
518
519 /**
520 * Generate a process error record, suitable for attachment to a ProcessRecord.
521 *
522 * @param app The ProcessRecord in which the error occurred.
523 * @param condition Crashing, Application Not Responding, etc. Values are defined in
524 * ActivityManager.AppErrorStateInfo
525 * @param activity The activity associated with the crash, if known.
526 * @param shortMsg Short message describing the crash.
527 * @param longMsg Long message describing the crash.
528 * @param stackTrace Full crash stack trace, may be null.
529 *
530 * @return Returns a fully-formed AppErrorStateInfo record.
531 */
532 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
533 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
534 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
535
536 report.condition = condition;
537 report.processName = app.processName;
538 report.pid = app.pid;
539 report.uid = app.info.uid;
540 report.tag = activity;
541 report.shortMsg = shortMsg;
542 report.longMsg = longMsg;
543 report.stackTrace = stackTrace;
544
545 return report;
546 }
547
548 Intent createAppErrorIntentLocked(ProcessRecord r,
549 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
550 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
551 if (report == null) {
552 return null;
553 }
554 Intent result = new Intent(Intent.ACTION_APP_ERROR);
555 result.setComponent(r.errorReportReceiver);
556 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
557 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
558 return result;
559 }
560
561 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
562 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
563 if (r.errorReportReceiver == null) {
564 return null;
565 }
566
567 if (!r.crashing && !r.notResponding && !r.forceCrashReport) {
568 return null;
569 }
570
571 ApplicationErrorReport report = new ApplicationErrorReport();
572 report.packageName = r.info.packageName;
573 report.installerPackageName = r.errorReportReceiver.getPackageName();
574 report.processName = r.processName;
575 report.time = timeMillis;
576 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
577
578 if (r.crashing || r.forceCrashReport) {
579 report.type = ApplicationErrorReport.TYPE_CRASH;
580 report.crashInfo = crashInfo;
581 } else if (r.notResponding) {
582 report.type = ApplicationErrorReport.TYPE_ANR;
583 report.anrInfo = new ApplicationErrorReport.AnrInfo();
584
585 report.anrInfo.activity = r.notRespondingReport.tag;
586 report.anrInfo.cause = r.notRespondingReport.shortMsg;
587 report.anrInfo.info = r.notRespondingReport.longMsg;
588 }
589
590 return report;
591 }
592
593 boolean handleAppCrashLocked(ProcessRecord app, String reason,
594 String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
595 long now = SystemClock.uptimeMillis();
Adrian Roos6a7e0892016-08-23 14:26:39 +0200596 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
597 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
Adrian Roos20d7df32016-01-12 18:59:43 +0100598
599 Long crashTime;
600 Long crashTimePersistent;
601 if (!app.isolated) {
602 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
603 crashTimePersistent = mProcessCrashTimesPersistent.get(app.info.processName, app.uid);
604 } else {
605 crashTime = crashTimePersistent = null;
606 }
607 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
608 // This process loses!
609 Slog.w(TAG, "Process " + app.info.processName
610 + " has crashed too many times: killing!");
611 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
612 app.userId, app.info.processName, app.uid);
613 mService.mStackSupervisor.handleAppCrashLocked(app);
614 if (!app.persistent) {
615 // We don't want to start this process again until the user
616 // explicitly does so... but for persistent process, we really
617 // need to keep it running. If a persistent process is actually
618 // repeatedly crashing, then badness for everyone.
619 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
620 app.info.processName);
621 if (!app.isolated) {
622 // XXX We don't have a way to mark isolated processes
623 // as bad, since they don't have a peristent identity.
624 mBadProcesses.put(app.info.processName, app.uid,
625 new BadProcessInfo(now, shortMsg, longMsg, stackTrace));
626 mProcessCrashTimes.remove(app.info.processName, app.uid);
627 }
628 app.bad = true;
629 app.removed = true;
630 // Don't let services in this process be restarted and potentially
631 // annoy the user repeatedly. Unless it is persistent, since those
632 // processes run critical code.
633 mService.removeProcessLocked(app, false, false, "crash");
634 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
Adrian Roos6a7e0892016-08-23 14:26:39 +0200635 if (!showBackground) {
636 return false;
637 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100638 }
639 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
640 } else {
641 TaskRecord affectedTask =
642 mService.mStackSupervisor.finishTopRunningActivityLocked(app, reason);
643 if (data != null) {
644 data.task = affectedTask;
645 }
646 if (data != null && crashTimePersistent != null
647 && now < crashTimePersistent + ProcessList.MIN_CRASH_INTERVAL) {
648 data.repeating = true;
649 }
650 }
651
Adrian Roos805ea302016-07-27 12:25:54 -0700652 boolean procIsBoundForeground =
653 (app.curProcState == ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
Adrian Roos20d7df32016-01-12 18:59:43 +0100654 // Bump up the crash count of any services currently running in the proc.
655 for (int i=app.services.size()-1; i>=0; i--) {
656 // Any services running in the application need to be placed
657 // back in the pending list.
658 ServiceRecord sr = app.services.valueAt(i);
659 sr.crashCount++;
Adrian Roos805ea302016-07-27 12:25:54 -0700660
661 // Allow restarting for started or bound foreground services that are crashing the
662 // first time. This includes wallpapers.
Erik Wolsheimerb2b3b642016-08-05 09:24:07 -0700663 if ((data != null) && (sr.crashCount <= 1)
664 && (sr.isForeground || procIsBoundForeground)) {
Adrian Roos805ea302016-07-27 12:25:54 -0700665 data.isRestartableForService = true;
666 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100667 }
668
669 // If the crashing process is what we consider to be the "home process" and it has been
670 // replaced by a third-party app, clear the package preferred activities from packages
671 // with a home activity running in the process to prevent a repeatedly crashing app
672 // from blocking the user to manually clear the list.
673 final ArrayList<ActivityRecord> activities = app.activities;
674 if (app == mService.mHomeProcess && activities.size() > 0
675 && (mService.mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
676 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
677 final ActivityRecord r = activities.get(activityNdx);
678 if (r.isHomeActivity()) {
679 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
680 try {
681 ActivityThread.getPackageManager()
682 .clearPackagePreferredActivities(r.packageName);
683 } catch (RemoteException c) {
684 // pm is in same process, this will never happen.
685 }
686 }
687 }
688 }
689
690 if (!app.isolated) {
691 // XXX Can't keep track of crash times for isolated processes,
692 // because they don't have a perisistent identity.
693 mProcessCrashTimes.put(app.info.processName, app.uid, now);
694 mProcessCrashTimesPersistent.put(app.info.processName, app.uid, now);
695 }
696
697 if (app.crashHandler != null) mService.mHandler.post(app.crashHandler);
698 return true;
699 }
700
701 void handleShowAppErrorUi(Message msg) {
702 AppErrorDialog.Data data = (AppErrorDialog.Data) msg.obj;
703 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
704 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
705 synchronized (mService) {
706 ProcessRecord proc = data.proc;
707 AppErrorResult res = data.result;
708 if (proc != null && proc.crashDialog != null) {
709 Slog.e(TAG, "App already has crash dialog: " + proc);
710 if (res != null) {
Adrian Roos90462222016-02-17 15:45:09 -0800711 res.set(AppErrorDialog.ALREADY_SHOWING);
Adrian Roos20d7df32016-01-12 18:59:43 +0100712 }
713 return;
714 }
715 boolean isBackground = (UserHandle.getAppId(proc.uid)
716 >= Process.FIRST_APPLICATION_UID
717 && proc.pid != MY_PID);
718 for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) {
719 isBackground &= (proc.userId != userId);
720 }
721 if (isBackground && !showBackground) {
722 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
723 if (res != null) {
Adrian Roos90462222016-02-17 15:45:09 -0800724 res.set(AppErrorDialog.BACKGROUND_USER);
Adrian Roos20d7df32016-01-12 18:59:43 +0100725 }
726 return;
727 }
728 final boolean crashSilenced = mAppsNotReportingCrashes != null &&
729 mAppsNotReportingCrashes.contains(proc.info.packageName);
Adrian Roos6a7e0892016-08-23 14:26:39 +0200730 if ((mService.canShowErrorDialogs() || showBackground) && !crashSilenced) {
Phil Weaver445fd2a2016-03-17 17:26:24 -0700731 proc.crashDialog = new AppErrorDialog(mContext, mService, data);
Adrian Roos20d7df32016-01-12 18:59:43 +0100732 } else {
733 // The device is asleep, so just pretend that the user
734 // saw a crash dialog and hit "force quit".
735 if (res != null) {
Adrian Roos90462222016-02-17 15:45:09 -0800736 res.set(AppErrorDialog.CANT_SHOW);
Adrian Roos20d7df32016-01-12 18:59:43 +0100737 }
738 }
739 }
Phil Weaver445fd2a2016-03-17 17:26:24 -0700740 // If we've created a crash dialog, show it without the lock held
741 if(data.proc.crashDialog != null) {
742 data.proc.crashDialog.show();
743 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100744 }
745
746 void stopReportingCrashesLocked(ProcessRecord proc) {
747 if (mAppsNotReportingCrashes == null) {
748 mAppsNotReportingCrashes = new ArraySet<>();
749 }
750 mAppsNotReportingCrashes.add(proc.info.packageName);
751 }
752
753 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
754 ActivityRecord parent, boolean aboveSystem, final String annotation) {
755 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
756 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
757
758 if (mService.mController != null) {
759 try {
760 // 0 == continue, -1 = kill process immediately
Adrian Roosa85a2c62016-01-26 09:14:22 -0800761 int res = mService.mController.appEarlyNotResponding(
762 app.processName, app.pid, annotation);
Adrian Roos20d7df32016-01-12 18:59:43 +0100763 if (res < 0 && app.pid != MY_PID) {
764 app.kill("anr", true);
765 }
766 } catch (RemoteException e) {
767 mService.mController = null;
768 Watchdog.getInstance().setActivityController(null);
769 }
770 }
771
772 long anrTime = SystemClock.uptimeMillis();
773 if (ActivityManagerService.MONITOR_CPU_USAGE) {
774 mService.updateCpuStatsNow();
775 }
776
Tim Murrayf0f9a822016-07-13 13:33:28 -0700777 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
778 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
779 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
780
781 boolean isSilentANR;
782
Adrian Roos20d7df32016-01-12 18:59:43 +0100783 synchronized (mService) {
784 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
785 if (mService.mShuttingDown) {
786 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
787 return;
788 } else if (app.notResponding) {
789 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
790 return;
791 } else if (app.crashing) {
792 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
793 return;
Tobias Lindskog313177d2015-02-03 11:45:58 +0100794 } else if (app.killedByAm) {
795 Slog.i(TAG, "App already killed by AM skipping ANR: " + app + " " + annotation);
796 return;
Mark Lu41d65f22016-03-23 19:08:44 +0800797 } else if (app.killed) {
798 Slog.i(TAG, "Skipping died app ANR: " + app + " " + annotation);
799 return;
Adrian Roos20d7df32016-01-12 18:59:43 +0100800 }
801
802 // In case we come through here for the same app before completing
803 // this one, mark as anring now so we will bail out.
804 app.notResponding = true;
805
806 // Log the ANR to the event log.
807 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
808 app.processName, app.info.flags, annotation);
809
810 // Dump thread traces as quickly as we can, starting with "interesting" processes.
811 firstPids.add(app.pid);
812
Tim Murrayf0f9a822016-07-13 13:33:28 -0700813 // Don't dump other PIDs if it's a background ANR
814 isSilentANR = !showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID;
815 if (!isSilentANR) {
816 int parentPid = app.pid;
817 if (parent != null && parent.app != null && parent.app.pid > 0) {
818 parentPid = parent.app.pid;
819 }
820 if (parentPid != app.pid) firstPids.add(parentPid);
Adrian Roos20d7df32016-01-12 18:59:43 +0100821
Tim Murrayf0f9a822016-07-13 13:33:28 -0700822 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Adrian Roos20d7df32016-01-12 18:59:43 +0100823
Tim Murrayf0f9a822016-07-13 13:33:28 -0700824 for (int i = mService.mLruProcesses.size() - 1; i >= 0; i--) {
825 ProcessRecord r = mService.mLruProcesses.get(i);
826 if (r != null && r.thread != null) {
827 int pid = r.pid;
828 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
829 if (r.persistent) {
830 firstPids.add(pid);
831 if (DEBUG_ANR) Slog.i(TAG, "Adding persistent proc: " + r);
832 } else {
833 lastPids.put(pid, Boolean.TRUE);
834 if (DEBUG_ANR) Slog.i(TAG, "Adding ANR proc: " + r);
835 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100836 }
837 }
838 }
839 }
840 }
841
842 // Log the ANR to the main log.
843 StringBuilder info = new StringBuilder();
844 info.setLength(0);
845 info.append("ANR in ").append(app.processName);
846 if (activity != null && activity.shortComponentName != null) {
847 info.append(" (").append(activity.shortComponentName).append(")");
848 }
849 info.append("\n");
850 info.append("PID: ").append(app.pid).append("\n");
851 if (annotation != null) {
852 info.append("Reason: ").append(annotation).append("\n");
853 }
854 if (parent != null && parent != activity) {
855 info.append("Parent: ").append(parent.shortComponentName).append("\n");
856 }
857
Tim Murrayf0f9a822016-07-13 13:33:28 -0700858 ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);
Adrian Roos20d7df32016-01-12 18:59:43 +0100859
Tim Murrayf0f9a822016-07-13 13:33:28 -0700860 String[] nativeProcs = NATIVE_STACKS_OF_INTEREST;
861 // don't dump native PIDs for background ANRs
862 File tracesFile = null;
863 if (isSilentANR) {
864 tracesFile = mService.dumpStackTraces(true, firstPids, null, lastPids,
865 null);
866 } else {
867 tracesFile = mService.dumpStackTraces(true, firstPids, processCpuTracker, lastPids,
868 nativeProcs);
869 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100870
871 String cpuInfo = null;
872 if (ActivityManagerService.MONITOR_CPU_USAGE) {
873 mService.updateCpuStatsNow();
874 synchronized (mService.mProcessCpuTracker) {
875 cpuInfo = mService.mProcessCpuTracker.printCurrentState(anrTime);
876 }
877 info.append(processCpuTracker.printCurrentLoad());
878 info.append(cpuInfo);
879 }
880
881 info.append(processCpuTracker.printCurrentState(anrTime));
882
883 Slog.e(TAG, info.toString());
884 if (tracesFile == null) {
885 // There is no trace file, so dump (only) the alleged culprit's threads to the log
886 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
887 }
888
889 mService.addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
890 cpuInfo, tracesFile, null);
891
892 if (mService.mController != null) {
893 try {
894 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
895 int res = mService.mController.appNotResponding(
896 app.processName, app.pid, info.toString());
897 if (res != 0) {
898 if (res < 0 && app.pid != MY_PID) {
899 app.kill("anr", true);
900 } else {
901 synchronized (mService) {
902 mService.mServices.scheduleServiceTimeoutLocked(app);
903 }
904 }
905 return;
906 }
907 } catch (RemoteException e) {
908 mService.mController = null;
909 Watchdog.getInstance().setActivityController(null);
910 }
911 }
912
Adrian Roos20d7df32016-01-12 18:59:43 +0100913 synchronized (mService) {
914 mService.mBatteryStatsService.noteProcessAnr(app.processName, app.uid);
915
Tim Murrayf0f9a822016-07-13 13:33:28 -0700916 if (isSilentANR) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100917 app.kill("bg anr", true);
918 return;
919 }
920
921 // Set the app's notResponding state, and look up the errorReportReceiver
922 makeAppNotRespondingLocked(app,
923 activity != null ? activity.shortComponentName : null,
924 annotation != null ? "ANR " + annotation : "ANR",
925 info.toString());
926
927 // Bring up the infamous App Not Responding dialog
928 Message msg = Message.obtain();
929 HashMap<String, Object> map = new HashMap<String, Object>();
930 msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG;
931 msg.obj = map;
932 msg.arg1 = aboveSystem ? 1 : 0;
933 map.put("app", app);
934 if (activity != null) {
935 map.put("activity", activity);
936 }
937
938 mService.mUiHandler.sendMessage(msg);
939 }
940 }
941
942 private void makeAppNotRespondingLocked(ProcessRecord app,
943 String activity, String shortMsg, String longMsg) {
944 app.notResponding = true;
945 app.notRespondingReport = generateProcessError(app,
946 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
947 activity, shortMsg, longMsg, null);
948 startAppProblemLocked(app);
949 app.stopFreezingAllLocked();
950 }
951
952 void handleShowAnrUi(Message msg) {
Phil Weaver445fd2a2016-03-17 17:26:24 -0700953 Dialog d = null;
Adrian Roos20d7df32016-01-12 18:59:43 +0100954 synchronized (mService) {
955 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
956 ProcessRecord proc = (ProcessRecord)data.get("app");
957 if (proc != null && proc.anrDialog != null) {
958 Slog.e(TAG, "App already has anr dialog: " + proc);
Adrian Roos90462222016-02-17 15:45:09 -0800959 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR,
960 AppNotRespondingDialog.ALREADY_SHOWING);
Adrian Roos20d7df32016-01-12 18:59:43 +0100961 return;
962 }
963
964 Intent intent = new Intent("android.intent.action.ANR");
965 if (!mService.mProcessesReady) {
966 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
967 | Intent.FLAG_RECEIVER_FOREGROUND);
968 }
969 mService.broadcastIntentLocked(null, null, intent,
970 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
971 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
972
Adrian Roos6a7e0892016-08-23 14:26:39 +0200973 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
974 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
975 if (mService.canShowErrorDialogs() || showBackground) {
Phil Weaver445fd2a2016-03-17 17:26:24 -0700976 d = new AppNotRespondingDialog(mService,
Adrian Roos20d7df32016-01-12 18:59:43 +0100977 mContext, proc, (ActivityRecord)data.get("activity"),
978 msg.arg1 != 0);
Adrian Roos20d7df32016-01-12 18:59:43 +0100979 proc.anrDialog = d;
980 } else {
Adrian Roos90462222016-02-17 15:45:09 -0800981 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR,
982 AppNotRespondingDialog.CANT_SHOW);
Adrian Roos20d7df32016-01-12 18:59:43 +0100983 // Just kill the app if there is no dialog to be shown.
984 mService.killAppAtUsersRequest(proc, null);
985 }
986 }
Phil Weaver445fd2a2016-03-17 17:26:24 -0700987 // If we've created a crash dialog, show it without the lock held
988 if (d != null) {
989 d.show();
990 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100991 }
992
993 /**
994 * Information about a process that is currently marked as bad.
995 */
996 static final class BadProcessInfo {
997 BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
998 this.time = time;
999 this.shortMsg = shortMsg;
1000 this.longMsg = longMsg;
1001 this.stack = stack;
1002 }
1003
1004 final long time;
1005 final String shortMsg;
1006 final String longMsg;
1007 final String stack;
1008 }
1009
1010}