2 * Copyright (C) 2016 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
17 package com.android.server.am;
19 import com.android.internal.app.ProcessMap;
20 import com.android.internal.logging.MetricsLogger;
21 import com.android.internal.logging.nano.MetricsProto;
22 import com.android.internal.os.ProcessCpuTracker;
23 import com.android.server.RescueParty;
24 import com.android.server.Watchdog;
26 import android.app.ActivityManager;
27 import android.app.ActivityOptions;
28 import android.app.ActivityThread;
29 import android.app.AppOpsManager;
30 import android.app.ApplicationErrorReport;
31 import android.app.Dialog;
32 import android.content.ActivityNotFoundException;
33 import android.content.Context;
34 import android.content.Intent;
35 import android.content.pm.ApplicationInfo;
36 import android.os.Binder;
37 import android.os.Message;
38 import android.os.Process;
39 import android.os.RemoteException;
40 import android.os.SystemClock;
41 import android.os.SystemProperties;
42 import android.os.UserHandle;
43 import android.provider.Settings;
44 import android.util.ArrayMap;
45 import android.util.ArraySet;
46 import android.util.EventLog;
47 import android.util.Log;
48 import android.util.Slog;
49 import android.util.SparseArray;
50 import android.util.TimeUtils;
53 import java.io.FileDescriptor;
54 import java.io.PrintWriter;
55 import java.util.ArrayList;
56 import java.util.Collections;
57 import java.util.HashMap;
58 import java.util.List;
61 import static com.android.server.Watchdog.NATIVE_STACKS_OF_INTEREST;
62 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_ANR;
63 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
64 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
65 import static com.android.server.am.ActivityManagerService.MY_PID;
66 import static com.android.server.am.ActivityManagerService.SYSTEM_DEBUGGABLE;
69 * Controls error conditions in applications.
73 private static final String TAG = TAG_WITH_CLASS_NAME ? "AppErrors" : TAG_AM;
75 private final ActivityManagerService mService;
76 private final Context mContext;
78 private ArraySet<String> mAppsNotReportingCrashes;
81 * The last time that various processes have crashed since they were last explicitly started.
83 private final ProcessMap<Long> mProcessCrashTimes = new ProcessMap<>();
86 * The last time that various processes have crashed (not reset even when explicitly started).
88 private final ProcessMap<Long> mProcessCrashTimesPersistent = new ProcessMap<>();
91 * Set of applications that we consider to be bad, and will reject
92 * incoming broadcasts from (which the user has no control over).
93 * Processes are added to this set when they have crashed twice within
94 * a minimum amount of time; they are removed from it when they are
95 * later restarted (hopefully due to some user action). The value is the
96 * time it was added to the list.
98 private final ProcessMap<BadProcessInfo> mBadProcesses = new ProcessMap<>();
101 AppErrors(Context context, ActivityManagerService service) {
102 context.assertRuntimeOverlayThemable();
107 boolean dumpLocked(FileDescriptor fd, PrintWriter pw, boolean needSep,
108 String dumpPackage) {
109 if (!mProcessCrashTimes.getMap().isEmpty()) {
110 boolean printed = false;
111 final long now = SystemClock.uptimeMillis();
112 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
113 final int processCount = pmap.size();
114 for (int ip = 0; ip < processCount; ip++) {
115 final String pname = pmap.keyAt(ip);
116 final SparseArray<Long> uids = pmap.valueAt(ip);
117 final int uidCount = uids.size();
118 for (int i = 0; i < uidCount; i++) {
119 final int puid = uids.keyAt(i);
120 final ProcessRecord r = mService.mProcessNames.get(pname, puid);
121 if (dumpPackage != null && (r == null
122 || !r.pkgList.containsKey(dumpPackage))) {
126 if (needSep) pw.println();
128 pw.println(" Time since processes crashed:");
131 pw.print(" Process "); pw.print(pname);
132 pw.print(" uid "); pw.print(puid);
133 pw.print(": last crashed ");
134 TimeUtils.formatDuration(now-uids.valueAt(i), pw);
140 if (!mBadProcesses.getMap().isEmpty()) {
141 boolean printed = false;
142 final ArrayMap<String, SparseArray<BadProcessInfo>> pmap = mBadProcesses.getMap();
143 final int processCount = pmap.size();
144 for (int ip = 0; ip < processCount; ip++) {
145 final String pname = pmap.keyAt(ip);
146 final SparseArray<BadProcessInfo> uids = pmap.valueAt(ip);
147 final int uidCount = uids.size();
148 for (int i = 0; i < uidCount; i++) {
149 final int puid = uids.keyAt(i);
150 final ProcessRecord r = mService.mProcessNames.get(pname, puid);
151 if (dumpPackage != null && (r == null
152 || !r.pkgList.containsKey(dumpPackage))) {
156 if (needSep) pw.println();
158 pw.println(" Bad processes:");
161 final BadProcessInfo info = uids.valueAt(i);
162 pw.print(" Bad process "); pw.print(pname);
163 pw.print(" uid "); pw.print(puid);
164 pw.print(": crashed at time "); pw.println(info.time);
165 if (info.shortMsg != null) {
166 pw.print(" Short msg: "); pw.println(info.shortMsg);
168 if (info.longMsg != null) {
169 pw.print(" Long msg: "); pw.println(info.longMsg);
171 if (info.stack != null) {
172 pw.println(" Stack:");
174 for (int pos = 0; pos < info.stack.length(); pos++) {
175 if (info.stack.charAt(pos) == '\n') {
177 pw.write(info.stack, lastPos, pos-lastPos);
182 if (lastPos < info.stack.length()) {
184 pw.write(info.stack, lastPos, info.stack.length()-lastPos);
194 boolean isBadProcessLocked(ApplicationInfo info) {
195 return mBadProcesses.get(info.processName, info.uid) != null;
198 void clearBadProcessLocked(ApplicationInfo info) {
199 mBadProcesses.remove(info.processName, info.uid);
202 void resetProcessCrashTimeLocked(ApplicationInfo info) {
203 mProcessCrashTimes.remove(info.processName, info.uid);
206 void resetProcessCrashTimeLocked(boolean resetEntireUser, int appId, int userId) {
207 final ArrayMap<String, SparseArray<Long>> pmap = mProcessCrashTimes.getMap();
208 for (int ip = pmap.size() - 1; ip >= 0; ip--) {
209 SparseArray<Long> ba = pmap.valueAt(ip);
210 for (int i = ba.size() - 1; i >= 0; i--) {
211 boolean remove = false;
212 final int entUid = ba.keyAt(i);
213 if (!resetEntireUser) {
214 if (userId == UserHandle.USER_ALL) {
215 if (UserHandle.getAppId(entUid) == appId) {
219 if (entUid == UserHandle.getUid(userId, appId)) {
223 } else if (UserHandle.getUserId(entUid) == userId) {
230 if (ba.size() == 0) {
236 void loadAppsNotReportingCrashesFromConfigLocked(String appsNotReportingCrashesConfig) {
237 if (appsNotReportingCrashesConfig != null) {
238 final String[] split = appsNotReportingCrashesConfig.split(",");
239 if (split.length > 0) {
240 mAppsNotReportingCrashes = new ArraySet<>();
241 Collections.addAll(mAppsNotReportingCrashes, split);
246 void killAppAtUserRequestLocked(ProcessRecord app, Dialog fromDialog) {
247 app.crashing = false;
248 app.crashingReport = null;
249 app.notResponding = false;
250 app.notRespondingReport = null;
251 if (app.anrDialog == fromDialog) {
252 app.anrDialog = null;
254 if (app.waitDialog == fromDialog) {
255 app.waitDialog = null;
257 if (app.pid > 0 && app.pid != MY_PID) {
258 handleAppCrashLocked(app, "user-terminated" /*reason*/,
259 null /*shortMsg*/, null /*longMsg*/, null /*stackTrace*/, null /*data*/);
260 app.kill("user request after error", true);
265 * Induce a crash in the given app.
267 * @param uid if nonnegative, the required matching uid of the target to crash
268 * @param initialPid fast-path match for the target to crash
269 * @param packageName fallback match if the stated pid is not found or doesn't match uid
270 * @param userId If nonnegative, required to identify a match by package name
273 void scheduleAppCrashLocked(int uid, int initialPid, String packageName, int userId,
275 ProcessRecord proc = null;
277 // Figure out which process to kill. We don't trust that initialPid
278 // still has any relation to current pids, so must scan through the
281 synchronized (mService.mPidsSelfLocked) {
282 for (int i=0; i<mService.mPidsSelfLocked.size(); i++) {
283 ProcessRecord p = mService.mPidsSelfLocked.valueAt(i);
284 if (uid >= 0 && p.uid != uid) {
287 if (p.pid == initialPid) {
291 if (p.pkgList.containsKey(packageName)
292 && (userId < 0 || p.userId == userId)) {
299 Slog.w(TAG, "crashApplication: nothing for uid=" + uid
300 + " initialPid=" + initialPid
301 + " packageName=" + packageName
302 + " userId=" + userId);
306 proc.scheduleCrash(message);
310 * Bring up the "unexpected error" dialog box for a crashing app.
311 * Deal with edge cases (intercepts from instrumented applications,
312 * ActivityController, error intent receivers, that sort of thing).
313 * @param r the application crashing
314 * @param crashInfo describing the failure
316 void crashApplication(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo) {
317 final int callingPid = Binder.getCallingPid();
318 final int callingUid = Binder.getCallingUid();
320 final long origId = Binder.clearCallingIdentity();
322 crashApplicationInner(r, crashInfo, callingPid, callingUid);
324 Binder.restoreCallingIdentity(origId);
328 void crashApplicationInner(ProcessRecord r, ApplicationErrorReport.CrashInfo crashInfo,
329 int callingPid, int callingUid) {
330 long timeMillis = System.currentTimeMillis();
331 String shortMsg = crashInfo.exceptionClassName;
332 String longMsg = crashInfo.exceptionMessage;
333 String stackTrace = crashInfo.stackTrace;
334 if (shortMsg != null && longMsg != null) {
335 longMsg = shortMsg + ": " + longMsg;
336 } else if (shortMsg != null) {
340 // If a persistent app is stuck in a crash loop, the device isn't very
341 // usable, so we want to consider sending out a rescue party.
342 if (r != null && r.persistent) {
343 RescueParty.notePersistentAppCrash(mContext, r.uid);
346 AppErrorResult result = new AppErrorResult();
348 synchronized (mService) {
350 * If crash is handled by instance of {@link android.app.IActivityController},
351 * finish now and don't show the app error dialog.
353 if (handleAppCrashInActivityController(r, crashInfo, shortMsg, longMsg, stackTrace,
354 timeMillis, callingPid, callingUid)) {
359 * If this process was running instrumentation, finish now - it will be handled in
360 * {@link ActivityManagerService#handleAppDiedLocked}.
362 if (r != null && r.instr != null) {
366 // Log crash in battery stats.
368 mService.mBatteryStatsService.noteProcessCrash(r.processName, r.uid);
371 AppErrorDialog.Data data = new AppErrorDialog.Data();
372 data.result = result;
375 // If we can't identify the process or it's already exceeded its crash quota,
376 // quit right away without showing a crash dialog.
377 if (r == null || !makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, data)) {
381 final Message msg = Message.obtain();
382 msg.what = ActivityManagerService.SHOW_ERROR_UI_MSG;
386 mService.mUiHandler.sendMessage(msg);
389 int res = result.get();
391 Intent appErrorIntent = null;
392 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_CRASH, res);
393 if (res == AppErrorDialog.TIMEOUT || res == AppErrorDialog.CANCEL) {
394 res = AppErrorDialog.FORCE_QUIT;
396 synchronized (mService) {
397 if (res == AppErrorDialog.MUTE) {
398 stopReportingCrashesLocked(r);
400 if (res == AppErrorDialog.RESTART) {
401 mService.removeProcessLocked(r, false, true, "crash");
404 mService.startActivityFromRecents(task.taskId,
405 ActivityOptions.makeBasic().toBundle());
406 } catch (IllegalArgumentException e) {
407 // Hmm, that didn't work, app might have crashed before creating a
408 // recents entry. Let's see if we have a safe-to-restart intent.
409 final Set<String> cats = task.intent.getCategories();
410 if (cats != null && cats.contains(Intent.CATEGORY_LAUNCHER)) {
411 mService.startActivityInPackage(task.mCallingUid,
412 task.mCallingPackage, task.intent,
413 null, null, null, 0, 0,
414 ActivityOptions.makeBasic().toBundle(),
415 task.userId, null, null, "AppErrors");
420 if (res == AppErrorDialog.FORCE_QUIT) {
421 long orig = Binder.clearCallingIdentity();
423 // Kill it with fire!
424 mService.mStackSupervisor.handleAppCrashLocked(r);
426 mService.removeProcessLocked(r, false, false, "crash");
427 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
430 Binder.restoreCallingIdentity(orig);
433 if (res == AppErrorDialog.FORCE_QUIT_AND_REPORT) {
434 appErrorIntent = createAppErrorIntentLocked(r, timeMillis, crashInfo);
436 if (r != null && !r.isolated && res != AppErrorDialog.RESTART) {
437 // XXX Can't keep track of crash time for isolated processes,
438 // since they don't have a persistent identity.
439 mProcessCrashTimes.put(r.info.processName, r.uid,
440 SystemClock.uptimeMillis());
444 if (appErrorIntent != null) {
446 mContext.startActivityAsUser(appErrorIntent, new UserHandle(r.userId));
447 } catch (ActivityNotFoundException e) {
448 Slog.w(TAG, "bug report receiver dissappeared", e);
453 private boolean handleAppCrashInActivityController(ProcessRecord r,
454 ApplicationErrorReport.CrashInfo crashInfo,
455 String shortMsg, String longMsg,
456 String stackTrace, long timeMillis,
457 int callingPid, int callingUid) {
458 if (mService.mController == null) {
463 String name = r != null ? r.processName : null;
464 int pid = r != null ? r.pid : callingPid;
465 int uid = r != null ? r.info.uid : callingUid;
466 if (!mService.mController.appCrashed(name, pid,
467 shortMsg, longMsg, timeMillis, crashInfo.stackTrace)) {
468 if ("1".equals(SystemProperties.get(SYSTEM_DEBUGGABLE, "0"))
469 && "Native crash".equals(crashInfo.exceptionClassName)) {
470 Slog.w(TAG, "Skip killing native crashed app " + name
471 + "(" + pid + ") during testing");
473 Slog.w(TAG, "Force-killing crashed app " + name
474 + " at watcher's request");
476 if (!makeAppCrashingLocked(r, shortMsg, longMsg, stackTrace, null))
478 r.kill("crash", true);
482 Process.killProcess(pid);
483 ActivityManagerService.killProcessGroup(uid, pid);
488 } catch (RemoteException e) {
489 mService.mController = null;
490 Watchdog.getInstance().setActivityController(null);
495 private boolean makeAppCrashingLocked(ProcessRecord app,
496 String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
498 app.crashingReport = generateProcessError(app,
499 ActivityManager.ProcessErrorStateInfo.CRASHED, null, shortMsg, longMsg, stackTrace);
500 startAppProblemLocked(app);
501 app.stopFreezingAllLocked();
502 return handleAppCrashLocked(app, "force-crash" /*reason*/, shortMsg, longMsg, stackTrace,
506 void startAppProblemLocked(ProcessRecord app) {
507 // If this app is not running under the current user, then we
508 // can't give it a report button because that would require
509 // launching the report UI under a different user.
510 app.errorReportReceiver = null;
512 for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) {
513 if (app.userId == userId) {
514 app.errorReportReceiver = ApplicationErrorReport.getErrorReportReceiver(
515 mContext, app.info.packageName, app.info.flags);
518 mService.skipCurrentReceiverLocked(app);
522 * Generate a process error record, suitable for attachment to a ProcessRecord.
524 * @param app The ProcessRecord in which the error occurred.
525 * @param condition Crashing, Application Not Responding, etc. Values are defined in
526 * ActivityManager.AppErrorStateInfo
527 * @param activity The activity associated with the crash, if known.
528 * @param shortMsg Short message describing the crash.
529 * @param longMsg Long message describing the crash.
530 * @param stackTrace Full crash stack trace, may be null.
532 * @return Returns a fully-formed AppErrorStateInfo record.
534 private ActivityManager.ProcessErrorStateInfo generateProcessError(ProcessRecord app,
535 int condition, String activity, String shortMsg, String longMsg, String stackTrace) {
536 ActivityManager.ProcessErrorStateInfo report = new ActivityManager.ProcessErrorStateInfo();
538 report.condition = condition;
539 report.processName = app.processName;
540 report.pid = app.pid;
541 report.uid = app.info.uid;
542 report.tag = activity;
543 report.shortMsg = shortMsg;
544 report.longMsg = longMsg;
545 report.stackTrace = stackTrace;
550 Intent createAppErrorIntentLocked(ProcessRecord r,
551 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
552 ApplicationErrorReport report = createAppErrorReportLocked(r, timeMillis, crashInfo);
553 if (report == null) {
556 Intent result = new Intent(Intent.ACTION_APP_ERROR);
557 result.setComponent(r.errorReportReceiver);
558 result.putExtra(Intent.EXTRA_BUG_REPORT, report);
559 result.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
563 private ApplicationErrorReport createAppErrorReportLocked(ProcessRecord r,
564 long timeMillis, ApplicationErrorReport.CrashInfo crashInfo) {
565 if (r.errorReportReceiver == null) {
569 if (!r.crashing && !r.notResponding && !r.forceCrashReport) {
573 ApplicationErrorReport report = new ApplicationErrorReport();
574 report.packageName = r.info.packageName;
575 report.installerPackageName = r.errorReportReceiver.getPackageName();
576 report.processName = r.processName;
577 report.time = timeMillis;
578 report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
580 if (r.crashing || r.forceCrashReport) {
581 report.type = ApplicationErrorReport.TYPE_CRASH;
582 report.crashInfo = crashInfo;
583 } else if (r.notResponding) {
584 report.type = ApplicationErrorReport.TYPE_ANR;
585 report.anrInfo = new ApplicationErrorReport.AnrInfo();
587 report.anrInfo.activity = r.notRespondingReport.tag;
588 report.anrInfo.cause = r.notRespondingReport.shortMsg;
589 report.anrInfo.info = r.notRespondingReport.longMsg;
595 boolean handleAppCrashLocked(ProcessRecord app, String reason,
596 String shortMsg, String longMsg, String stackTrace, AppErrorDialog.Data data) {
597 long now = SystemClock.uptimeMillis();
598 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
599 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
602 Long crashTimePersistent;
604 crashTime = mProcessCrashTimes.get(app.info.processName, app.uid);
605 crashTimePersistent = mProcessCrashTimesPersistent.get(app.info.processName, app.uid);
607 crashTime = crashTimePersistent = null;
609 if (crashTime != null && now < crashTime+ProcessList.MIN_CRASH_INTERVAL) {
610 // This process loses!
611 Slog.w(TAG, "Process " + app.info.processName
612 + " has crashed too many times: killing!");
613 EventLog.writeEvent(EventLogTags.AM_PROCESS_CRASHED_TOO_MUCH,
614 app.userId, app.info.processName, app.uid);
615 mService.mStackSupervisor.handleAppCrashLocked(app);
616 if (!app.persistent) {
617 // We don't want to start this process again until the user
618 // explicitly does so... but for persistent process, we really
619 // need to keep it running. If a persistent process is actually
620 // repeatedly crashing, then badness for everyone.
621 EventLog.writeEvent(EventLogTags.AM_PROC_BAD, app.userId, app.uid,
622 app.info.processName);
624 // XXX We don't have a way to mark isolated processes
625 // as bad, since they don't have a peristent identity.
626 mBadProcesses.put(app.info.processName, app.uid,
627 new BadProcessInfo(now, shortMsg, longMsg, stackTrace));
628 mProcessCrashTimes.remove(app.info.processName, app.uid);
632 // Don't let services in this process be restarted and potentially
633 // annoy the user repeatedly. Unless it is persistent, since those
634 // processes run critical code.
635 mService.removeProcessLocked(app, false, false, "crash");
636 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
637 if (!showBackground) {
641 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
643 TaskRecord affectedTask =
644 mService.mStackSupervisor.finishTopRunningActivityLocked(app, reason);
646 data.task = affectedTask;
648 if (data != null && crashTimePersistent != null
649 && now < crashTimePersistent + ProcessList.MIN_CRASH_INTERVAL) {
650 data.repeating = true;
654 boolean procIsBoundForeground =
655 (app.curProcState == ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE);
656 // Bump up the crash count of any services currently running in the proc.
657 for (int i=app.services.size()-1; i>=0; i--) {
658 // Any services running in the application need to be placed
659 // back in the pending list.
660 ServiceRecord sr = app.services.valueAt(i);
663 // Allow restarting for started or bound foreground services that are crashing the
664 // first time. This includes wallpapers.
665 if ((data != null) && (sr.crashCount <= 1)
666 && (sr.isForeground || procIsBoundForeground)) {
667 data.isRestartableForService = true;
671 // If the crashing process is what we consider to be the "home process" and it has been
672 // replaced by a third-party app, clear the package preferred activities from packages
673 // with a home activity running in the process to prevent a repeatedly crashing app
674 // from blocking the user to manually clear the list.
675 final ArrayList<ActivityRecord> activities = app.activities;
676 if (app == mService.mHomeProcess && activities.size() > 0
677 && (mService.mHomeProcess.info.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
678 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
679 final ActivityRecord r = activities.get(activityNdx);
680 if (r.isHomeActivity()) {
681 Log.i(TAG, "Clearing package preferred activities from " + r.packageName);
683 ActivityThread.getPackageManager()
684 .clearPackagePreferredActivities(r.packageName);
685 } catch (RemoteException c) {
686 // pm is in same process, this will never happen.
693 // XXX Can't keep track of crash times for isolated processes,
694 // because they don't have a perisistent identity.
695 mProcessCrashTimes.put(app.info.processName, app.uid, now);
696 mProcessCrashTimesPersistent.put(app.info.processName, app.uid, now);
699 if (app.crashHandler != null) mService.mHandler.post(app.crashHandler);
703 void handleShowAppErrorUi(Message msg) {
704 AppErrorDialog.Data data = (AppErrorDialog.Data) msg.obj;
705 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
706 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
707 synchronized (mService) {
708 ProcessRecord proc = data.proc;
709 AppErrorResult res = data.result;
710 if (proc != null && proc.crashDialog != null) {
711 Slog.e(TAG, "App already has crash dialog: " + proc);
713 res.set(AppErrorDialog.ALREADY_SHOWING);
717 boolean isBackground = (UserHandle.getAppId(proc.uid)
718 >= Process.FIRST_APPLICATION_UID
719 && proc.pid != MY_PID);
720 for (int userId : mService.mUserController.getCurrentProfileIdsLocked()) {
721 isBackground &= (proc.userId != userId);
723 if (isBackground && !showBackground) {
724 Slog.w(TAG, "Skipping crash dialog of " + proc + ": background");
726 res.set(AppErrorDialog.BACKGROUND_USER);
730 final boolean crashSilenced = mAppsNotReportingCrashes != null &&
731 mAppsNotReportingCrashes.contains(proc.info.packageName);
732 if ((mService.canShowErrorDialogs() || showBackground) && !crashSilenced) {
733 proc.crashDialog = new AppErrorDialog(mContext, mService, data);
735 // The device is asleep, so just pretend that the user
736 // saw a crash dialog and hit "force quit".
738 res.set(AppErrorDialog.CANT_SHOW);
742 // If we've created a crash dialog, show it without the lock held
743 if(data.proc.crashDialog != null) {
744 Slog.i(TAG, "Showing crash dialog for package " + data.proc.info.packageName
745 + " u" + data.proc.userId);
746 data.proc.crashDialog.show();
750 void stopReportingCrashesLocked(ProcessRecord proc) {
751 if (mAppsNotReportingCrashes == null) {
752 mAppsNotReportingCrashes = new ArraySet<>();
754 mAppsNotReportingCrashes.add(proc.info.packageName);
757 static boolean isInterestingForBackgroundTraces(ProcessRecord app) {
758 // The system_server is always considered interesting.
759 if (app.pid == MY_PID) {
763 // A package is considered interesting if any of the following is true :
765 // - It's displaying an activity.
766 // - It's the SystemUI.
767 // - It has an overlay or a top UI visible.
769 // NOTE: The check whether a given ProcessRecord belongs to the systemui
770 // process is a bit of a kludge, but the same pattern seems repeated at
771 // several places in the system server.
772 return app.isInterestingToUserLocked() ||
773 (app.info != null && "com.android.systemui".equals(app.info.packageName)) ||
774 (app.hasTopUi || app.hasOverlayUi);
777 final void appNotResponding(ProcessRecord app, ActivityRecord activity,
778 ActivityRecord parent, boolean aboveSystem, final String annotation) {
779 ArrayList<Integer> firstPids = new ArrayList<Integer>(5);
780 SparseArray<Boolean> lastPids = new SparseArray<Boolean>(20);
782 if (mService.mController != null) {
784 // 0 == continue, -1 = kill process immediately
785 int res = mService.mController.appEarlyNotResponding(
786 app.processName, app.pid, annotation);
787 if (res < 0 && app.pid != MY_PID) {
788 app.kill("anr", true);
790 } catch (RemoteException e) {
791 mService.mController = null;
792 Watchdog.getInstance().setActivityController(null);
796 long anrTime = SystemClock.uptimeMillis();
797 if (ActivityManagerService.MONITOR_CPU_USAGE) {
798 mService.updateCpuStatsNow();
801 // Unless configured otherwise, swallow ANRs in background processes & kill the process.
802 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
803 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
807 synchronized (mService) {
808 // PowerManager.reboot() can block for a long time, so ignore ANRs while shutting down.
809 if (mService.mShuttingDown) {
810 Slog.i(TAG, "During shutdown skipping ANR: " + app + " " + annotation);
812 } else if (app.notResponding) {
813 Slog.i(TAG, "Skipping duplicate ANR: " + app + " " + annotation);
815 } else if (app.crashing) {
816 Slog.i(TAG, "Crashing app skipping ANR: " + app + " " + annotation);
818 } else if (app.killedByAm) {
819 Slog.i(TAG, "App already killed by AM skipping ANR: " + app + " " + annotation);
821 } else if (app.killed) {
822 Slog.i(TAG, "Skipping died app ANR: " + app + " " + annotation);
826 // In case we come through here for the same app before completing
827 // this one, mark as anring now so we will bail out.
828 app.notResponding = true;
830 // Log the ANR to the event log.
831 EventLog.writeEvent(EventLogTags.AM_ANR, app.userId, app.pid,
832 app.processName, app.info.flags, annotation);
834 // Dump thread traces as quickly as we can, starting with "interesting" processes.
835 firstPids.add(app.pid);
837 // Don't dump other PIDs if it's a background ANR
838 isSilentANR = !showBackground && !isInterestingForBackgroundTraces(app);
840 int parentPid = app.pid;
841 if (parent != null && parent.app != null && parent.app.pid > 0) {
842 parentPid = parent.app.pid;
844 if (parentPid != app.pid) firstPids.add(parentPid);
846 if (MY_PID != app.pid && MY_PID != parentPid) firstPids.add(MY_PID);
848 for (int i = mService.mLruProcesses.size() - 1; i >= 0; i--) {
849 ProcessRecord r = mService.mLruProcesses.get(i);
850 if (r != null && r.thread != null) {
852 if (pid > 0 && pid != app.pid && pid != parentPid && pid != MY_PID) {
855 if (DEBUG_ANR) Slog.i(TAG, "Adding persistent proc: " + r);
856 } else if (r.treatLikeActivity) {
858 if (DEBUG_ANR) Slog.i(TAG, "Adding likely IME: " + r);
860 lastPids.put(pid, Boolean.TRUE);
861 if (DEBUG_ANR) Slog.i(TAG, "Adding ANR proc: " + r);
869 // Log the ANR to the main log.
870 StringBuilder info = new StringBuilder();
872 info.append("ANR in ").append(app.processName);
873 if (activity != null && activity.shortComponentName != null) {
874 info.append(" (").append(activity.shortComponentName).append(")");
877 info.append("PID: ").append(app.pid).append("\n");
878 if (annotation != null) {
879 info.append("Reason: ").append(annotation).append("\n");
881 if (parent != null && parent != activity) {
882 info.append("Parent: ").append(parent.shortComponentName).append("\n");
885 ProcessCpuTracker processCpuTracker = new ProcessCpuTracker(true);
887 // don't dump native PIDs for background ANRs unless it is the process of interest
888 String[] nativeProcs = null;
890 for (int i = 0; i < NATIVE_STACKS_OF_INTEREST.length; i++) {
891 if (NATIVE_STACKS_OF_INTEREST[i].equals(app.processName)) {
892 nativeProcs = new String[] { app.processName };
897 nativeProcs = NATIVE_STACKS_OF_INTEREST;
900 int[] pids = nativeProcs == null ? null : Process.getPidsForCommands(nativeProcs);
901 ArrayList<Integer> nativePids = null;
904 nativePids = new ArrayList<Integer>(pids.length);
910 // For background ANRs, don't pass the ProcessCpuTracker to
911 // avoid spending 1/2 second collecting stats to rank lastPids.
912 File tracesFile = ActivityManagerService.dumpStackTraces(
914 (isSilentANR) ? null : processCpuTracker,
915 (isSilentANR) ? null : lastPids,
918 String cpuInfo = null;
919 if (ActivityManagerService.MONITOR_CPU_USAGE) {
920 mService.updateCpuStatsNow();
921 synchronized (mService.mProcessCpuTracker) {
922 cpuInfo = mService.mProcessCpuTracker.printCurrentState(anrTime);
924 info.append(processCpuTracker.printCurrentLoad());
925 info.append(cpuInfo);
928 info.append(processCpuTracker.printCurrentState(anrTime));
930 Slog.e(TAG, info.toString());
931 if (tracesFile == null) {
932 // There is no trace file, so dump (only) the alleged culprit's threads to the log
933 Process.sendSignal(app.pid, Process.SIGNAL_QUIT);
936 mService.addErrorToDropBox("anr", app, app.processName, activity, parent, annotation,
937 cpuInfo, tracesFile, null);
939 if (mService.mController != null) {
941 // 0 == show dialog, 1 = keep waiting, -1 = kill process immediately
942 int res = mService.mController.appNotResponding(
943 app.processName, app.pid, info.toString());
945 if (res < 0 && app.pid != MY_PID) {
946 app.kill("anr", true);
948 synchronized (mService) {
949 mService.mServices.scheduleServiceTimeoutLocked(app);
954 } catch (RemoteException e) {
955 mService.mController = null;
956 Watchdog.getInstance().setActivityController(null);
960 synchronized (mService) {
961 mService.mBatteryStatsService.noteProcessAnr(app.processName, app.uid);
964 app.kill("bg anr", true);
968 // Set the app's notResponding state, and look up the errorReportReceiver
969 makeAppNotRespondingLocked(app,
970 activity != null ? activity.shortComponentName : null,
971 annotation != null ? "ANR " + annotation : "ANR",
974 // Bring up the infamous App Not Responding dialog
975 Message msg = Message.obtain();
976 HashMap<String, Object> map = new HashMap<String, Object>();
977 msg.what = ActivityManagerService.SHOW_NOT_RESPONDING_UI_MSG;
979 msg.arg1 = aboveSystem ? 1 : 0;
981 if (activity != null) {
982 map.put("activity", activity);
985 mService.mUiHandler.sendMessage(msg);
989 private void makeAppNotRespondingLocked(ProcessRecord app,
990 String activity, String shortMsg, String longMsg) {
991 app.notResponding = true;
992 app.notRespondingReport = generateProcessError(app,
993 ActivityManager.ProcessErrorStateInfo.NOT_RESPONDING,
994 activity, shortMsg, longMsg, null);
995 startAppProblemLocked(app);
996 app.stopFreezingAllLocked();
999 void handleShowAnrUi(Message msg) {
1001 synchronized (mService) {
1002 HashMap<String, Object> data = (HashMap<String, Object>) msg.obj;
1003 ProcessRecord proc = (ProcessRecord)data.get("app");
1004 if (proc != null && proc.anrDialog != null) {
1005 Slog.e(TAG, "App already has anr dialog: " + proc);
1006 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR,
1007 AppNotRespondingDialog.ALREADY_SHOWING);
1011 Intent intent = new Intent("android.intent.action.ANR");
1012 if (!mService.mProcessesReady) {
1013 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1014 | Intent.FLAG_RECEIVER_FOREGROUND);
1016 mService.broadcastIntentLocked(null, null, intent,
1017 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1018 null, false, false, MY_PID, Process.SYSTEM_UID, 0 /* TODO: Verify */);
1020 boolean showBackground = Settings.Secure.getInt(mContext.getContentResolver(),
1021 Settings.Secure.ANR_SHOW_BACKGROUND, 0) != 0;
1022 if (mService.canShowErrorDialogs() || showBackground) {
1023 d = new AppNotRespondingDialog(mService,
1024 mContext, proc, (ActivityRecord)data.get("activity"),
1028 MetricsLogger.action(mContext, MetricsProto.MetricsEvent.ACTION_APP_ANR,
1029 AppNotRespondingDialog.CANT_SHOW);
1030 // Just kill the app if there is no dialog to be shown.
1031 mService.killAppAtUsersRequest(proc, null);
1034 // If we've created a crash dialog, show it without the lock held
1041 * Information about a process that is currently marked as bad.
1043 static final class BadProcessInfo {
1044 BadProcessInfo(long time, String shortMsg, String longMsg, String stack) {
1046 this.shortMsg = shortMsg;
1047 this.longMsg = longMsg;
1052 final String shortMsg;
1053 final String longMsg;