blob: 7eff773543c8f0e0bd793a09e16adf5c57707a6b [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;
21import com.android.internal.logging.MetricsProto;
Adrian Roos20d7df32016-01-12 18:59:43 +010022import com.android.internal.os.ProcessCpuTracker;
23import com.android.server.Watchdog;
24
25import android.app.Activity;
26import 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;
36import android.content.pm.IPackageDataObserver;
37import android.content.pm.PackageManager;
38import android.os.Binder;
39import android.os.Bundle;
40import android.os.Message;
41import android.os.Process;
42import android.os.RemoteException;
43import android.os.SystemClock;
44import android.os.SystemProperties;
45import android.os.UserHandle;
46import android.provider.Settings;
47import android.util.ArrayMap;
48import android.util.ArraySet;
49import android.util.EventLog;
50import android.util.Log;
51import android.util.Slog;
52import android.util.SparseArray;
53import android.util.TimeUtils;
54
55import java.io.File;
56import java.io.FileDescriptor;
57import java.io.PrintWriter;
58import java.util.ArrayList;
59import java.util.Collections;
60import java.util.HashMap;
Dianne Hackborn4d895942016-07-12 13:36:02 -070061import java.util.Set;
Adrian Roos20d7df32016-01-12 18:59:43 +010062import java.util.concurrent.Semaphore;
63
64import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST;
Dianne Hackborn9369efd2016-03-02 15:49:58 -080065import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
Adrian Roos20d7df32016-01-12 18:59:43 +010066import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
67import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
68import static com.android.server.am.ActivityManagerService.MY_PID;
69import static com.android.server.am.ActivityManagerService.SYSTEM_DEBUGGABLE;
70
71/**
72 * Controls error conditions in applications.
73 */
74class AppErrors {
75
76 private static final String TAG = TAG_WITH_CLASS_NAME ? "AppErrors" : TAG_AM;
77
78 private final ActivityManagerService mService;
79 private final Context mContext;
80
81 private ArraySet<String> mAppsNotReportingCrashes;
82
83 /**
84 * The last time that various processes have crashed since they were last explicitly started.
85 */
86 private final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<>();
87
88 /**
89 * The last time that various processes have crashed (not reset even when explicitly started).
90 */
91 private final ProcessMap<Long> mProcessCrashTimesPersistent = new ProcessMap<>();
92
93 /**
94 * Set of applications that we consider to be bad, and will reject
95 * incoming broadcasts from (which the user has no control over).
96 * Processes are added to this set when they have crashed twice within
97 * a minimum amount of time; they are removed from it when they are
98 * later restarted (hopefully due to some user action). The value is the
99 * time it was added to the list.
100 */
101 private final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<>();
102
103
104 AppErrors(Context context, ActivityManagerService service) {
105 mService = service;
106 mContext = context;
107 }
108
109 boolean dumpLocked(FileDescriptor fd, PrintWriter pw, boolean needSep,
110 String dumpPackage) {
111 if (!mProcessCrashTimes.getMap().isEmpty()) {
112 boolean printed = false;
113 final long now = SystemClock.uptimeMillis();
114 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
115 final int processCount = pmap.size();
116 for (int ip = 0; ip < processCount; ip++) {
117 final String pname = pmap.keyAt(ip);
118 final SparseArray<Long> uids = pmap.valueAt(ip);
119 final int uidCount = uids.size();
120 for (int i = 0; i < uidCount; i++) {
121 final int puid = uids.keyAt(i);
122 final ProcessRecord r = mService.mProcessNames.get(pname, puid);
123 if (dumpPackage != null && (r == null
124 || !r.pkgList.containsKey(dumpPackage))) {
125 continue;
126 }
127 if (!printed) {
128 if (needSep) pw.println();
129 needSep = true;
130 pw.println(" Time since processes crashed:");
131 printed = true;
132 }
133 pw.print(" Process "); pw.print(pname);
134 pw.print(" uid "); pw.print(puid);
135 pw.print(": last crashed ");
136 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
137 pw.println(" ago");
138 }
139 }
140 }
141
142 if (!mBadProcesses.getMap().isEmpty()) {
143 boolean printed = false;
144 final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap();
145 final int processCount = pmap.size();
146 for (int ip = 0; ip < processCount; ip++) {
147 final String pname = pmap.keyAt(ip);
148 final SparseArray<BadProcessInfo> uids = pmap.valueAt(ip);
149 final int uidCount = uids.size();
150 for (int i = 0; i < uidCount; i++) {
151 final int puid = uids.keyAt(i);
152 final ProcessRecord r = mService.mProcessNames.get(pname, puid);
153 if (dumpPackage != null && (r == null
154 || !r.pkgList.containsKey(dumpPackage))) {
155 continue;
156 }
157 if (!printed) {
158 if (needSep) pw.println();
159 needSep = true;
160 pw.println(" Bad processes:");
161 printed = true;
162 }
163 final BadProcessInfo info = uids.valueAt(i);
164 pw.print(" Bad process "); pw.print(pname);
165 pw.print(" uid "); pw.print(puid);
166 pw.print(": crashed at time "); pw.println(info.time);
167 if (info.shortMsg != null) {
168 pw.print(" Short msg: "); pw.println(info.shortMsg);
169 }
170 if (info.longMsg != null) {
171 pw.print(" Long msg: "); pw.println(info.longMsg);
172 }
173 if (info.stack != null) {
174 pw.println(" Stack:");
175 int lastPos = 0;
176 for (int pos = 0; pos < info.stack.length(); pos++) {
177 if (info.stack.charAt(pos) == '\n') {
178 pw.print(" ");
179 pw.write(info.stack, lastPos, pos-lastPos);
180 pw.println();
181 lastPos = pos+1;
182 }
183 }
184 if (lastPos < info.stack.length()) {
185 pw.print(" ");
186 pw.write(info.stack, lastPos, info.stack.length()-lastPos);
187 pw.println();
188 }
189 }
190 }
191 }
192 }
193 return needSep;
194 }
195
196 boolean isBadProcessLocked(ApplicationInfo info) {
197 return mBadProcesses.get(info.processName, info.uid) != null;
198 }
199
200 void clearBadProcessLocked(ApplicationInfo info) {
201 mBadProcesses.remove(info.processName, info.uid);
202 }
203
204 void resetProcessCrashTimeLocked(ApplicationInfo info) {
205 mProcessCrashTimes.remove(info.processName, info.uid);
206 }
207
208 void resetProcessCrashTimeLocked(boolean resetEntireUser, int appId, int userId) {
209 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
210 for (int ip = pmap.size() - 1; ip >= 0; ip--) {
211 SparseArray<Long> ba = pmap.valueAt(ip);
212 for (int i = ba.size() - 1; i >= 0; i--) {
213 boolean remove = false;
214 final int entUid = ba.keyAt(i);
215 if (!resetEntireUser) {
216 if (userId == UserHandle.USER_ALL) {
217 if (UserHandle.getAppId(entUid) == appId) {
218 remove = true;
219 }
220 } else {
221 if (entUid == UserHandle.getUid(userId, appId)) {
222 remove = true;
223 }
224 }
225 } else if (UserHandle.getUserId(entUid) == userId) {
226 remove = true;
227 }
228 if (remove) {
229 ba.removeAt(i);
230 }
231 }
232 if (ba.size() == 0) {
233 pmap.removeAt(ip);
234 }
235 }
236 }
237
238 void loadAppsNotReportingCrashesFromConfigLocked(String appsNotReportingCrashesConfig) {
239 if (appsNotReportingCrashesConfig != null) {
240 final String[] split = appsNotReportingCrashesConfig.split(",");
241 if (split.length > 0) {
242 mAppsNotReportingCrashes = new ArraySet<>();
243 Collections.addAll(mAppsNotReportingCrashes, split);
244 }
245 }
246 }
247
248 void killAppAtUserRequestLocked(ProcessRecord app, Dialog fromDialog) {
249 app.crashing = false;
250 app.crashingReport = null;
251 app.notResponding = false;
252 app.notRespondingReport = null;
253 if (app.anrDialog == fromDialog) {
254 app.anrDialog = null;
255 }
256 if (app.waitDialog == fromDialog) {
257 app.waitDialog = null;
258 }
259 if (app.pid > 0 && app.pid != MY_PID) {
260 handleAppCrashLocked(app, "user-terminated" /*reason*/,
261 null /*shortMsg*/, null /*longMsg*/, null /*stackTrace*/, null /*data*/);
262 app.kill("user request after error", true);
263 }
264 }
265
266 void scheduleAppCrashLocked(int uid, int initialPid, String packageName,
267 String message) {
268 ProcessRecord proc = null;
269
270 // Figure out which process to kill. We don't trust that initialPid
271 // still has any relation to current pids, so must scan through the
272 // list.
273
274 synchronized (mService.mPidsSelfLocked) {
275 for (int i=0; i<mService.mPidsSelfLocked.size(); i++) {
276 ProcessRecord p = mService.mPidsSelfLocked.valueAt(i);
277 if (p.uid != uid) {
278 continue;
279 }
280 if (p.pid == initialPid) {
281 proc = p;
282 break;
283 }
284 if (p.pkgList.containsKey(packageName)) {
285 proc = p;
286 }
287 }
288 }
289
290 if (proc == null) {
291 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
292 + " initialPid=" + initialPid
293 + " packageName=" + packageName);
294 return;
295 }
296
Joe Onorato57190282016-04-20 15:37:49 -0700297 proc.scheduleCrash(message);
Adrian Roos20d7df32016-01-12 18:59:43 +0100298 }
299
300 /**
301 * Bring up the "unexpected error" dialog box for a crashing app.
302 * Deal with edge cases (intercepts from instrumented applications,
303 * ActivityController, error intent receivers, that sort of thing).
304 * @param r the application crashing
305 * @param crashInfo describing the failure
306 */
307 void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700308 final long origId = Binder.clearCallingIdentity();
309 try {
310 crashApplicationInner(r, crashInfo);
311 } finally {
312 Binder.restoreCallingIdentity(origId);
313 }
314 }
315
316 void crashApplicationInner(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100317 long timeMillis = System.currentTimeMillis();
318 String shortMsg = crashInfo.exceptionClassName;
319 String longMsg = crashInfo.exceptionMessage;
320 String stackTrace = crashInfo.stackTrace;
321 if (shortMsg != null && longMsg != null) {
322 longMsg = shortMsg + ": " + longMsg;
323 } else if (shortMsg != null) {
324 longMsg = shortMsg;
325 }
326
327 AppErrorResult result = new AppErrorResult();
328 TaskRecord task;
329 synchronized (mService) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700330 /**
331 * If crash is handled by instance of {@link android.app.IActivityController},
332 * finish now and don't show the app error dialog.
333 */
334 if (handleAppCrashInActivityController(r, crashInfo, shortMsg, longMsg, stackTrace,
335 timeMillis)) {
336 return;
Adrian Roos20d7df32016-01-12 18:59:43 +0100337 }
338
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700339 /**
340 * If this process was running instrumentation, finish now - it will be handled in
341 * {@link ActivityManagerService#handleAppDiedLocked}.
342 */
Adrian Roos20d7df32016-01-12 18:59:43 +0100343 if (r != null && r.instrumentationClass != null) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100344 return;
345 }
346
347 // Log crash in battery stats.
348 if (r != null) {
349 mService.mBatteryStatsService.noteProcessCrash(r.processName, r.uid);
350 }
351
352 AppErrorDialog.Data data = new AppErrorDialog.Data();
353 data.result = result;
354 data.proc = r;
355
356 // If we can't identify the process or it's already exceeded its crash quota,
357 // quit right away without showing a crash dialog.
358 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, data)) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100359 return;
360 }
361
362 Message msg = Message.obtain();
363 msg.what = ActivityManagerService.SHOW_ERROR_UI_MSG;
364
365 task = data.task;
366 msg.obj = data;
367 mService.mUiHandler.sendMessage(msg);
Adrian Roos20d7df32016-01-12 18:59:43 +0100368 }
369
370 int res = result.get();
371
372 Intent appErrorIntent = null;
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700373 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_CRASH, res);
Adrian Roosad028c12016-05-17 14:30:42 -0700374 if (res == AppErrorDialog.TIMEOUT || res == AppErrorDialog.CANCEL) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700375 res = AppErrorDialog.FORCE_QUIT;
376 }
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700377 synchronized (mService) {
378 if (res == AppErrorDialog.MUTE) {
379 stopReportingCrashesLocked(r);
380 }
381 if (res == AppErrorDialog.RESTART) {
382 mService.removeProcessLocked(r, false, true, "crash");
383 if (task != null) {
384 try {
385 mService.startActivityFromRecents(task.taskId,
386 ActivityOptions.makeBasic().toBundle());
387 } catch (IllegalArgumentException e) {
388 // Hmm, that didn't work, app might have crashed before creating a
389 // recents entry. Let's see if we have a safe-to-restart intent.
Dianne Hackborn4d895942016-07-12 13:36:02 -0700390 final Set<String> cats = task.intent.getCategories();
391 if (cats != null && cats.contains(Intent.CATEGORY_LAUNCHER)) {
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700392 mService.startActivityInPackage(task.mCallingUid,
393 task.mCallingPackage, task.intent,
394 null, null, null, 0, 0,
395 ActivityOptions.makeBasic().toBundle(),
396 task.userId, null, null);
397 }
398 }
399 }
400 }
401 if (res == AppErrorDialog.FORCE_QUIT) {
402 long orig = Binder.clearCallingIdentity();
403 try {
404 // Kill it with fire!
405 mService.mStackSupervisor.handleAppCrashLocked(r);
406 if (!r.persistent) {
407 mService.removeProcessLocked(r, false, false, "crash");
408 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
409 }
410 } finally {
411 Binder.restoreCallingIdentity(orig);
412 }
413 }
414 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
415 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
416 }
417 if (r != null && !r.isolated && res != AppErrorDialog.RESTART) {
418 // XXX Can't keep track of crash time for isolated processes,
419 // since they don't have a persistent identity.
420 mProcessCrashTimes.put(r.info.processName, r.uid,
421 SystemClock.uptimeMillis());
422 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100423 }
424
425 if (appErrorIntent != null) {
426 try {
427 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
428 } catch (ActivityNotFoundException e) {
429 Slog.w(TAG, "bug report receiver dissappeared", e);
430 }
431 }
432 }
433
Andrii Kulianfa3991a2016-04-28 14:18:37 -0700434 private boolean handleAppCrashInActivityController(ProcessRecord r,
435 ApplicationErrorReport.CrashInfo crashInfo,
436 String shortMsg, String longMsg,
437 String stackTrace, long timeMillis) {
438 if (mService.mController == null) {
439 return false;
440 }
441
442 try {
443 String name = r != null ? r.processName : null;
444 int pid = r != null ? r.pid : Binder.getCallingPid();
445 int uid = r != null ? r.info.uid : Binder.getCallingUid();
446 if (!mService.mController.appCrashed(name, pid,
447 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
448 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"))
449 && "Native crash".equals(crashInfo.exceptionClassName)) {
450 Slog.w(TAG, "Skip killing native crashed app " + name
451 + "(" + pid + ") during testing");
452 } else {
453 Slog.w(TAG, "Force-killing crashed app " + name
454 + " at watcher's request");
455 if (r != null) {
456 if (!makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, null))
457 {
458 r.kill("crash", true);
459 }
460 } else {
461 // Huh.
462 Process.killProcess(pid);
463 ActivityManagerService.killProcessGroup(uid, pid);
464 }
465 }
466 return true;
467 }
468 } catch (RemoteException e) {
469 mService.mController = null;
470 Watchdog.getInstance().setActivityController(null);
471 }
472 return false;
473 }
474
Adrian Roos20d7df32016-01-12 18:59:43 +0100475 private boolean makeAppCrashingLocked(ProcessRecord app,
476 String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
477 app.crashing = true;
478 app.crashingReport = generateProcessError(app,
479 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
480 startAppProblemLocked(app);
481 app.stopFreezingAllLocked();
482 return handleAppCrashLocked(app, "force-crash" /*reason*/, shortMsg, longMsg, stackTrace,
483 data);
484 }
485
486 void startAppProblemLocked(ProcessRecord app) {
487 // If this app is not running under the current user, then we
488 // can't give it a report button because that would require
489 // launching the report UI under a different user.
490 app.errorReportReceiver = null;
491
492 for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) {
493 if (app.userId == userId) {
494 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
495 mContext, app.info.packageName, app.info.flags);
496 }
497 }
498 mService.skipCurrentReceiverLocked(app);
499 }
500
501 /**
502 * Generate a process error record, suitable for attachment to a ProcessRecord.
503 *
504 * @param app The ProcessRecord in which the error occurred.
505 * @param condition Crashing, Application Not Responding, etc. Values are defined in
506 * ActivityManager.AppErrorStateInfo
507 * @param activity The activity associated with the crash, if known.
508 * @param shortMsg Short message describing the crash.
509 * @param longMsg Long message describing the crash.
510 * @param stackTrace Full crash stack trace, may be null.
511 *
512 * @return Returns a fully-formed AppErrorStateInfo record.
513 */
514 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
515 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
516 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
517
518 report.condition = condition;
519 report.processName = app.processName;
520 report.pid = app.pid;
521 report.uid = app.info.uid;
522 report.tag = activity;
523 report.shortMsg = shortMsg;
524 report.longMsg = longMsg;
525 report.stackTrace = stackTrace;
526
527 return report;
528 }
529
530 Intent createAppErrorIntentLocked(ProcessRecord r,
531 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
532 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
533 if (report == null) {
534 return null;
535 }
536 Intent result = new Intent(Intent.ACTION_APP_ERROR);
537 result.setComponent(r.errorReportReceiver);
538 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
539 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
540 return result;
541 }
542
543 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
544 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
545 if (r.errorReportReceiver == null) {
546 return null;
547 }
548
549 if (!r.crashing && !r.notResponding && !r.forceCrashReport) {
550 return null;
551 }
552
553 ApplicationErrorReport report = new ApplicationErrorReport();
554 report.packageName = r.info.packageName;
555 report.installerPackageName = r.errorReportReceiver.getPackageName();
556 report.processName = r.processName;
557 report.time = timeMillis;
558 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
559
560 if (r.crashing || r.forceCrashReport) {
561 report.type = ApplicationErrorReport.TYPE_CRASH;
562 report.crashInfo = crashInfo;
563 } else if (r.notResponding) {
564 report.type = ApplicationErrorReport.TYPE_ANR;
565 report.anrInfo = new ApplicationErrorReport.AnrInfo();
566
567 report.anrInfo.activity = r.notRespondingReport.tag;
568 report.anrInfo.cause = r.notRespondingReport.shortMsg;
569 report.anrInfo.info = r.notRespondingReport.longMsg;
570 }
571
572 return report;
573 }
574
575 boolean handleAppCrashLocked(ProcessRecord app, String reason,
576 String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
577 long now = SystemClock.uptimeMillis();
578
579 Long crashTime;
580 Long crashTimePersistent;
581 if (!app.isolated) {
582 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
583 crashTimePersistent = mProcessCrashTimesPersistent.get(app.info.processName, app.uid);
584 } else {
585 crashTime = crashTimePersistent = null;
586 }
587 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
588 // This process loses!
589 Slog.w(TAG, "Process " + app.info.processName
590 + " has crashed too many times: killing!");
591 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
592 app.userId, app.info.processName, app.uid);
593 mService.mStackSupervisor.handleAppCrashLocked(app);
594 if (!app.persistent) {
595 // We don't want to start this process again until the user
596 // explicitly does so... but for persistent process, we really
597 // need to keep it running. If a persistent process is actually
598 // repeatedly crashing, then badness for everyone.
599 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
600 app.info.processName);
601 if (!app.isolated) {
602 // XXX We don't have a way to mark isolated processes
603 // as bad, since they don't have a peristent identity.
604 mBadProcesses.put(app.info.processName, app.uid,
605 new BadProcessInfo(now, shortMsg, longMsg, stackTrace));
606 mProcessCrashTimes.remove(app.info.processName, app.uid);
607 }
608 app.bad = true;
609 app.removed = true;
610 // Don't let services in this process be restarted and potentially
611 // annoy the user repeatedly. Unless it is persistent, since those
612 // processes run critical code.
613 mService.removeProcessLocked(app, false, false, "crash");
614 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
615 return false;
616 }
617 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
618 } else {
619 TaskRecord affectedTask =
620 mService.mStackSupervisor.finishTopRunningActivityLocked(app, reason);
621 if (data != null) {
622 data.task = affectedTask;
623 }
624 if (data != null && crashTimePersistent != null
625 && now < crashTimePersistent + ProcessList.MIN_CRASH_INTERVAL) {
626 data.repeating = true;
627 }
628 }
629
Adrian Roos805ea302016-07-27 12:25:54 -0700630 boolean procIsBoundForeground =
631 (app.curProcState == ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
Adrian Roos20d7df32016-01-12 18:59:43 +0100632 // Bump up the crash count of any services currently running in the proc.
633 for (int i=app.services.size()-1; i>=0; i--) {
634 // Any services running in the application need to be placed
635 // back in the pending list.
636 ServiceRecord sr = app.services.valueAt(i);
637 sr.crashCount++;
Adrian Roos805ea302016-07-27 12:25:54 -0700638
639 // Allow restarting for started or bound foreground services that are crashing the
640 // first time. This includes wallpapers.
Erik Wolsheimerb2b3b642016-08-05 09:24:07 -0700641 if ((data != null) && (sr.crashCount <= 1)
642 && (sr.isForeground || procIsBoundForeground)) {
Adrian Roos805ea302016-07-27 12:25:54 -0700643 data.isRestartableForService = true;
644 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100645 }
646
647 // If the crashing process is what we consider to be the "home process" and it has been
648 // replaced by a third-party app, clear the package preferred activities from packages
649 // with a home activity running in the process to prevent a repeatedly crashing app
650 // from blocking the user to manually clear the list.
651 final ArrayList<ActivityRecord> activities = app.activities;
652 if (app == mService.mHomeProcess && activities.size() > 0
653 && (mService.mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
654 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
655 final ActivityRecord r = activities.get(activityNdx);
656 if (r.isHomeActivity()) {
657 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
658 try {
659 ActivityThread.getPackageManager()
660 .clearPackagePreferredActivities(r.packageName);
661 } catch (RemoteException c) {
662 // pm is in same process, this will never happen.
663 }
664 }
665 }
666 }
667
668 if (!app.isolated) {
669 // XXX Can't keep track of crash times for isolated processes,
670 // because they don't have a perisistent identity.
671 mProcessCrashTimes.put(app.info.processName, app.uid, now);
672 mProcessCrashTimesPersistent.put(app.info.processName, app.uid, now);
673 }
674
675 if (app.crashHandler != null) mService.mHandler.post(app.crashHandler);
676 return true;
677 }
678
679 void handleShowAppErrorUi(Message msg) {
680 AppErrorDialog.Data data = (AppErrorDialog.Data) msg.obj;
681 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
682 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
683 synchronized (mService) {
684 ProcessRecord proc = data.proc;
685 AppErrorResult res = data.result;
686 if (proc != null && proc.crashDialog != null) {
687 Slog.e(TAG, "App already has crash dialog: " + proc);
688 if (res != null) {
Adrian Roos90462222016-02-17 15:45:09 -0800689 res.set(AppErrorDialog.ALREADY_SHOWING);
Adrian Roos20d7df32016-01-12 18:59:43 +0100690 }
691 return;
692 }
693 boolean isBackground = (UserHandle.getAppId(proc.uid)
694 >= Process.FIRST_APPLICATION_UID
695 && proc.pid != MY_PID);
696 for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) {
697 isBackground &= (proc.userId != userId);
698 }
699 if (isBackground && !showBackground) {
700 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
701 if (res != null) {
Adrian Roos90462222016-02-17 15:45:09 -0800702 res.set(AppErrorDialog.BACKGROUND_USER);
Adrian Roos20d7df32016-01-12 18:59:43 +0100703 }
704 return;
705 }
706 final boolean crashSilenced = mAppsNotReportingCrashes != null &&
707 mAppsNotReportingCrashes.contains(proc.info.packageName);
708 if (mService.canShowErrorDialogs() && !crashSilenced) {
Phil Weaver445fd2a2016-03-17 17:26:24 -0700709 proc.crashDialog = new AppErrorDialog(mContext, mService, data);
Adrian Roos20d7df32016-01-12 18:59:43 +0100710 } else {
711 // The device is asleep, so just pretend that the user
712 // saw a crash dialog and hit "force quit".
713 if (res != null) {
Adrian Roos90462222016-02-17 15:45:09 -0800714 res.set(AppErrorDialog.CANT_SHOW);
Adrian Roos20d7df32016-01-12 18:59:43 +0100715 }
716 }
717 }
Phil Weaver445fd2a2016-03-17 17:26:24 -0700718 // If we've created a crash dialog, show it without the lock held
719 if(data.proc.crashDialog != null) {
720 data.proc.crashDialog.show();
721 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100722 }
723
724 void stopReportingCrashesLocked(ProcessRecord proc) {
725 if (mAppsNotReportingCrashes == null) {
726 mAppsNotReportingCrashes = new ArraySet<>();
727 }
728 mAppsNotReportingCrashes.add(proc.info.packageName);
729 }
730
731 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
732 ActivityRecord parent, boolean aboveSystem, final String annotation) {
733 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
734 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
735
736 if (mService.mController != null) {
737 try {
738 // 0 == continue, -1 = kill process immediately
Adrian Roosa85a2c62016-01-26 09:14:22 -0800739 int res = mService.mController.appEarlyNotResponding(
740 app.processName, app.pid, annotation);
Adrian Roos20d7df32016-01-12 18:59:43 +0100741 if (res < 0 && app.pid != MY_PID) {
742 app.kill("anr", true);
743 }
744 } catch (RemoteException e) {
745 mService.mController = null;
746 Watchdog.getInstance().setActivityController(null);
747 }
748 }
749
750 long anrTime = SystemClock.uptimeMillis();
751 if (ActivityManagerService.MONITOR_CPU_USAGE) {
752 mService.updateCpuStatsNow();
753 }
754
Tim Murrayf0f9a822016-07-13 13:33:28 -0700755 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
756 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
757 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
758
759 boolean isSilentANR;
760
Adrian Roos20d7df32016-01-12 18:59:43 +0100761 synchronized (mService) {
762 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
763 if (mService.mShuttingDown) {
764 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
765 return;
766 } else if (app.notResponding) {
767 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
768 return;
769 } else if (app.crashing) {
770 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
771 return;
772 }
773
774 // In case we come through here for the same app before completing
775 // this one, mark as anring now so we will bail out.
776 app.notResponding = true;
777
778 // Log the ANR to the event log.
779 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
780 app.processName, app.info.flags, annotation);
781
782 // Dump thread traces as quickly as we can, starting with "interesting" processes.
783 firstPids.add(app.pid);
784
Tim Murrayf0f9a822016-07-13 13:33:28 -0700785 // Don't dump other PIDs if it's a background ANR
786 isSilentANR = !showBackground && !app.isInterestingToUserLocked() && app.pid != MY_PID;
787 if (!isSilentANR) {
788 int parentPid = app.pid;
789 if (parent != null && parent.app != null && parent.app.pid > 0) {
790 parentPid = parent.app.pid;
791 }
792 if (parentPid != app.pid) firstPids.add(parentPid);
Adrian Roos20d7df32016-01-12 18:59:43 +0100793
Tim Murrayf0f9a822016-07-13 13:33:28 -0700794 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
Adrian Roos20d7df32016-01-12 18:59:43 +0100795
Tim Murrayf0f9a822016-07-13 13:33:28 -0700796 for (int i = mService.mLruProcesses.size() - 1; i >= 0; i--) {
797 ProcessRecord r = mService.mLruProcesses.get(i);
798 if (r != null && r.thread != null) {
799 int pid = r.pid;
800 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
801 if (r.persistent) {
802 firstPids.add(pid);
803 if (DEBUG_ANR) Slog.i(TAG, "Adding persistent proc: " + r);
804 } else {
805 lastPids.put(pid, Boolean.TRUE);
806 if (DEBUG_ANR) Slog.i(TAG, "Adding ANR proc: " + r);
807 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100808 }
809 }
810 }
811 }
812 }
813
814 // Log the ANR to the main log.
815 StringBuilder info = new StringBuilder();
816 info.setLength(0);
817 info.append("ANR in ").append(app.processName);
818 if (activity != null && activity.shortComponentName != null) {
819 info.append(" (").append(activity.shortComponentName).append(")");
820 }
821 info.append("\n");
822 info.append("PID: ").append(app.pid).append("\n");
823 if (annotation != null) {
824 info.append("Reason: ").append(annotation).append("\n");
825 }
826 if (parent != null && parent != activity) {
827 info.append("Parent: ").append(parent.shortComponentName).append("\n");
828 }
829
Tim Murrayf0f9a822016-07-13 13:33:28 -0700830 ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);
Adrian Roos20d7df32016-01-12 18:59:43 +0100831
Tim Murrayf0f9a822016-07-13 13:33:28 -0700832 String[] nativeProcs = NATIVE_STACKS_OF_INTEREST;
833 // don't dump native PIDs for background ANRs
834 File tracesFile = null;
835 if (isSilentANR) {
836 tracesFile = mService.dumpStackTraces(true, firstPids, null, lastPids,
837 null);
838 } else {
839 tracesFile = mService.dumpStackTraces(true, firstPids, processCpuTracker, lastPids,
840 nativeProcs);
841 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100842
843 String cpuInfo = null;
844 if (ActivityManagerService.MONITOR_CPU_USAGE) {
845 mService.updateCpuStatsNow();
846 synchronized (mService.mProcessCpuTracker) {
847 cpuInfo = mService.mProcessCpuTracker.printCurrentState(anrTime);
848 }
849 info.append(processCpuTracker.printCurrentLoad());
850 info.append(cpuInfo);
851 }
852
853 info.append(processCpuTracker.printCurrentState(anrTime));
854
855 Slog.e(TAG, info.toString());
856 if (tracesFile == null) {
857 // There is no trace file, so dump (only) the alleged culprit's threads to the log
858 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
859 }
860
861 mService.addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
862 cpuInfo, tracesFile, null);
863
864 if (mService.mController != null) {
865 try {
866 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
867 int res = mService.mController.appNotResponding(
868 app.processName, app.pid, info.toString());
869 if (res != 0) {
870 if (res < 0 && app.pid != MY_PID) {
871 app.kill("anr", true);
872 } else {
873 synchronized (mService) {
874 mService.mServices.scheduleServiceTimeoutLocked(app);
875 }
876 }
877 return;
878 }
879 } catch (RemoteException e) {
880 mService.mController = null;
881 Watchdog.getInstance().setActivityController(null);
882 }
883 }
884
Adrian Roos20d7df32016-01-12 18:59:43 +0100885 synchronized (mService) {
886 mService.mBatteryStatsService.noteProcessAnr(app.processName, app.uid);
887
Tim Murrayf0f9a822016-07-13 13:33:28 -0700888 if (isSilentANR) {
Adrian Roos20d7df32016-01-12 18:59:43 +0100889 app.kill("bg anr", true);
890 return;
891 }
892
893 // Set the app's notResponding state, and look up the errorReportReceiver
894 makeAppNotRespondingLocked(app,
895 activity != null ? activity.shortComponentName : null,
896 annotation != null ? "ANR " + annotation : "ANR",
897 info.toString());
898
899 // Bring up the infamous App Not Responding dialog
900 Message msg = Message.obtain();
901 HashMap<String, Object> map = new HashMap<String, Object>();
902 msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG;
903 msg.obj = map;
904 msg.arg1 = aboveSystem ? 1 : 0;
905 map.put("app", app);
906 if (activity != null) {
907 map.put("activity", activity);
908 }
909
910 mService.mUiHandler.sendMessage(msg);
911 }
912 }
913
914 private void makeAppNotRespondingLocked(ProcessRecord app,
915 String activity, String shortMsg, String longMsg) {
916 app.notResponding = true;
917 app.notRespondingReport = generateProcessError(app,
918 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
919 activity, shortMsg, longMsg, null);
920 startAppProblemLocked(app);
921 app.stopFreezingAllLocked();
922 }
923
924 void handleShowAnrUi(Message msg) {
Phil Weaver445fd2a2016-03-17 17:26:24 -0700925 Dialog d = null;
Adrian Roos20d7df32016-01-12 18:59:43 +0100926 synchronized (mService) {
927 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
928 ProcessRecord proc = (ProcessRecord)data.get("app");
929 if (proc != null && proc.anrDialog != null) {
930 Slog.e(TAG, "App already has anr dialog: " + proc);
Adrian Roos90462222016-02-17 15:45:09 -0800931 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR,
932 AppNotRespondingDialog.ALREADY_SHOWING);
Adrian Roos20d7df32016-01-12 18:59:43 +0100933 return;
934 }
935
936 Intent intent = new Intent("android.intent.action.ANR");
937 if (!mService.mProcessesReady) {
938 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
939 | Intent.FLAG_RECEIVER_FOREGROUND);
940 }
941 mService.broadcastIntentLocked(null, null, intent,
942 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
943 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
944
945 if (mService.canShowErrorDialogs()) {
Phil Weaver445fd2a2016-03-17 17:26:24 -0700946 d = new AppNotRespondingDialog(mService,
Adrian Roos20d7df32016-01-12 18:59:43 +0100947 mContext, proc, (ActivityRecord)data.get("activity"),
948 msg.arg1 != 0);
Adrian Roos20d7df32016-01-12 18:59:43 +0100949 proc.anrDialog = d;
950 } else {
Adrian Roos90462222016-02-17 15:45:09 -0800951 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR,
952 AppNotRespondingDialog.CANT_SHOW);
Adrian Roos20d7df32016-01-12 18:59:43 +0100953 // Just kill the app if there is no dialog to be shown.
954 mService.killAppAtUsersRequest(proc, null);
955 }
956 }
Phil Weaver445fd2a2016-03-17 17:26:24 -0700957 // If we've created a crash dialog, show it without the lock held
958 if (d != null) {
959 d.show();
960 }
Adrian Roos20d7df32016-01-12 18:59:43 +0100961 }
962
963 /**
964 * Information about a process that is currently marked as bad.
965 */
966 static final class BadProcessInfo {
967 BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
968 this.time = time;
969 this.shortMsg = shortMsg;
970 this.longMsg = longMsg;
971 this.stack = stack;
972 }
973
974 final long time;
975 final String shortMsg;
976 final String longMsg;
977 final String stack;
978 }
979
980}